Stack Exchange
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

So, In return value what i have to return ?

you need to define buffer as static: static char buffer[2048]; and then return buffer;

Also as @Acom said you need to remove this line memset(buffer, 0, size); and define buffer as following static char buffer[2048] = {0};

i tried with same, whatever you suggest me. but iam getting same error,

This is UB:
int size;
memset(buffer, 0, size);

since size is not initialized.
