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));
}
1
  • no you dont have to return the adress of TEMP data as you passed it by reference. Commented Apr 18, 2013 at 3:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.