Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of Realloc

Tags:

c

realloc

This is the way I've been taught to use realloc():

int *a = malloc(10);
a = realloc(a, 100); // Why do we do "a = .... ?"
if(a == NULL) 
//Deal with problem.....

Isn't that redundant? Can't i just do something like this? :

if(realloc(a, 100) == NULL) //Deal with the problem

Same for other realloc examples i've found around, for example:

int *oldPtr = malloc(10);
int * newPtr = realloc(oldPtr, 100);
if(newPtr == NULL) //deal with problems
else oldPtr = newPtr;

Can't i just do this instead? :

int *oldPtr = malloc(10);
if(realloc(oldPtr, 100) == NULL)  //deal with problems
//else not necessary, oldPtr has already been reallocated and has now 100 elements
like image 418
Sir_Playsalot Avatar asked Jun 27 '17 20:06

Sir_Playsalot


2 Answers

realloc returns a pointer to the resized buffer; this pointer value may be different from the original pointer value, so you need to save that return value somewhere.

realloc may return NULL if the request cannot be satsified (in which case the original buffer is left in place). For that reason, you want to save the return value to a different pointer variable than the original. Otherwise, you risk overwriting your original pointer with NULL and losing your only reference to that buffer.

Example:

size_t buf_size = 0; // keep track of our buffer size

// ...

int *a = malloc(sizeof *a * some_size); // initial allocation
if (a)
    buf_size = some_size;

// ...

int *tmp = realloc(a, sizeof *a * new_size); // reallocation
if (tmp) {
    a = tmp;             // save new pointer value
    buf_size = new_size; // and new buffer size
}
else {
    // realloc failure, handle as appropriate
}
like image 170
John Bode Avatar answered Sep 22 '22 03:09

John Bode


the correct way to call realloc is to save the return value in a temporary variable and check it for NULL. That way if realloc has failed, you haven't lost your original memory. For example:

int *a, *b;
a = malloc(10); 
b = realloc(a, 100);
if (b == NULL) {
    // handle error and exit
}
a = b;

EDIT: Note that if the error handling doesn't exit, you should put the last line above, i.e. a = b; inside an else clause.

like image 28
bruceg Avatar answered Sep 19 '22 03:09

bruceg