cstructmallocstrcpycjson

Using malloc with a structure and strcpy


I'm attempting to make an array of the structure I made called StatusItem, which looks like this:

typedef struct 
{
    char* name;
    char* index;
    int optional;
} StatusItem;

Also, as I want this array to be of any size, I am using malloc. So the array is defined as such:

StatusItem* statusItem = NULL;

(its then passed to function which retrieves all the values as follows.)

statusItem = (StatusItem*)malloc(cJSON_GetArraySize(items));

...

for (i = 0 ; i < cJSON_GetArraySize(items) ; i++)
{
    strcpy(statusItem[i].name,name->valuestring);
    strcpy(statusItem[i].index,index->valuestring);
    if(!parseInt(optional->valuestring, &statusItem[i].optional));
    {
         goto cleanup;
    }
}

There's come code that involves the cJSON library in getting the string values of name, index and optional into the variables referenced above, and they are stored in the valuestring field of those variables.

I have checked that everything involving the cJSON library works fine, and returns the correct values, but the program is unable to access or store values in the statusItems array.

Any ideas? I'm almost positive that it involves some misuse of malloc on my part.


Solution

  • To avoid having to use strdup() which is a little 'messier' because it leaves the freeing of the memory up to the caller instead of taking care of everything itself, I modified my existing structure as follows:

    typedef struct 
    {
        char name[32];
        char index[32];
        int optional;
    } StatusItem;
    

    This allows 32 bytes for the name and index, which should be more than enough. Before, the structures fields were pointing to nothing, which was causing the error when trying to copy to that location. now, there is empty (or junk) memory waiting for the string to be placed in.

    This allows for strcpy() to still be used, and allows for an overall cleaner implementation.