Search code examples
cstringmemory-managementstructrealloc

Using realloc to shrink the string inside struct


I have a small question about using the realloc function. Assuming I have:

typedef struct
{
  char* location;
  int temp;
  int numberOfRec;
 }TEMP;

Then I declare a pointer to this struct in the main and allocate the memory:

int main()
{ 
  TEMP* data = xCalloc (1, sizeof(TEMP));  //wrapper function
  data->location = xCalloc (20, sizeof(char)); //wrapper function

}

Now if I reallocate the memory for data->location in another function. Do I need to return the address of TEMP* data?

int main()
{

 someFunction(data); // Use this function or...
 //data = someFunction(data);
 ...
}
void someFunction(TEMP* data)
{
  ...
  data->location = xRealloc (data->location, 10 * sizeof(char));
}

Solution

  • No. You don't. This is because data is a pointer to the structure. Whenever you access an element of the structure through data using the '->' operator, you are first de-referencing the pointer.

    For example,

    data->location ==> (*data).location

    Also, when you do,

    data->location = xRealloc (data->location, 10 * sizeof(char));

    if the realloc fails, you would be leaking memory and possibly invoking undefined behaviour (if you don't include NULL pointer checks) because data->location has not been freed and it will be assigned to NULL since realloc returns NULL on failure.

    I suggest you do the following instead.

    void *temp = NULL;
    temp = xRealloc (data->location, 10 * sizeof(char));
    if(temp == NULL)
    {
        // realloc failed.
        free(data->location);
        data->location = NULL;
    }
    else
    {
        // Continue
        data->location = temp;
    }
    

    I compiled a minimal example for you.