0

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));
}
KurodaTsubasa
  • 25
  • 2
  • 5

1 Answers1

1

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.

Anish Ramaswamy
  • 2,326
  • 3
  • 32
  • 63
  • Thank you for your answer. Yes, I am aware of the need to have checks for these functions. I have actually done them in wrapper.c so I don't need to recheck in main source file. Thanks anyway! – KurodaTsubasa Apr 18 '13 at 05:03