/* If you are going to use realloc, don't make this common mistake! */

<stdlib.h>

int main (void) {

size_t size = 16;

char * ptr = malloc(size);

size = 32;

/* This is wrong!

ptr = realloc(ptr, size);

ptr is allocated. If this call fails ptr will be set to NULL, and
the allocated memory will not be freed.
*/

char * tmp_ptr = realloc(ptr, size);
if (NULL != tmp_ptr) {
ptr = tmp_ptr;
} else {
/* This is the error case */
free(ptr);
ptr = NULL;
}

free(ptr);
}

Follow

Oh, yeah, on that line right above the free(ptr); second from the bottom... That is where you might want to do something with ptr :) Sorry, I meant to put that in there.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.