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
realloc
might return a different pointer and invalidate the old one. Readman realloc
. – Wonderworkrealloc()
fails. – Tertianrealloc(...., 0)
is not necessarily an out-of-memory.realloc(...., more_than_zero)
returnsNULL
on out-of-memory and also may/may not return a non-out-of-memoryNULL
onrealloc(...., 0)
. – Lemming