简体   繁体   中英

Segmentation Fault in an Array using C

I was getting Segmentation fault for below Function[Sensor_Data]. In that function iam doing json format to pass attribute to buffer.

My code is below:

char *Json_Data = " ";
    char *Sensor_Data(void)
{
        char time[256];
        char buffer[2048];
        char temp[256] = {0};
        int size;
        memset(buffer, 0, size);

        printf("\n Sensor data Function.... ");
        sprintf(temp,"{\"Unique_ID\":\"%s\",", Uni_ID);
        strcpy(buffer, temp);
        memset(temp, 0, sizeof(temp));

        sprintf(temp, "\"Time\":\"%s\",", time);
        strcat(buffer, temp);
        memset(temp, 0, sizeof(temp));

        sprintf(temp, "\"humidity\":\"%s\",", 2345);
        strcat(buffer,temp);
        memset(temp, 0, sizeof(temp));

        sprintf(temp, "{\"X_axis\":\"%f\",\"Y_axis\":\"%f\",\"Z_axis\":\"%f\",", 18.234, 10.678, 13.345);
        strcat(buffer, temp);
        memset(temp, 0, sizeof(temp));

        strcat(buffer,"}}");
        printf("FRAME_FINAL_PACKET buffer %s\n",buffer);

        return 0;
}

Main Function:

int main(void)
{
        int rc = 0, count = 0;
        rc = cloud_init();
        if (rc != 0)
                printf("\n Cloud_init failed.\n");

        Json_Data = Sensor_Data();

        while(count <= 10)
        {
                rc = HTTPConnection(Json_Data);
                sleep(15000);
                count++;
        }
        if(rc != 0)
                printf("\n\n HTTP Connection Failed.. \n ");
}

int HTTPConnection(char *Json_Data)
{
        .........
        ..........

        rc = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, Json_Data);
        
        .........
        ........
}

Can anyone tell me where iam wrong.. why it giving segmentation fault?? Thanks in advance

Your function Sensor_Data(void) is returning 0

so the variable Json_Data will get 0 (NULL)

and then you will use the NULL as argument in the function HTTPConnection(char *Json_Data)

Most probably this is the cause of your crash

This is UB:

int size;
memset(buffer, 0, size);

since size is not initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM