Home > Back-end >  If realloc returns NULL do I have to free old memory?
If realloc returns NULL do I have to free old memory?

Time:06-25

So I know that realloc() can follow 2 ways. The first way is allocating memory in a new address and freeing old memory. Second way is allocating memory in the same address so that you will only need to free that address. So in both ways, you only have to free the address that realloc() allocates. But, what would happen if realloc() returned NULL, do I have to free old memory like this? :

//so in the first way, as b would be another address, a would be freed and if b is NULL it is no necessary to free it. But, if it follows second way, b will be same address as a and if it is NULL, I need to free old memory (a), right? 
int *a = (int*)malloc(sizeof(int));
int *b = (int*)realloc(a,sizeof(int)*3);

if(!b){
   free(a);
}

CodePudding user response:

If in this code snippet

int *a = (int*)malloc(sizeof(int));
int *b = (int*)realloc(a,sizeof(int)*3);

the function realloc will return NULL then in this case the early allocated memory will not be freed.

So how the program or the function should behave in this case depends on the context. You can free the previously allocated memory

free( a );

or continue to deal with the previously allocated memory taking into account that realloc failed.

  • Related