What happens to the original pointer after reallocating to a temporary one?

Question:

I am developing an application that requires a bit of excessive memory allocation/freeing and re-allocation, but I have a doubt regarding the use of the realloc(void *, size_t) function, I have the following code:

void Resize(void *ptr, size_t sz) {
    if (ptr == NULL || sz == 0) 
        return;                   /* No se ve afectado. */

    void *tmp = realloc(ptr, sz); /* Aquí sucede mi problema. */

    if (tmp == NULL) 
        return;                   /* No pasa nada en caso de NULL */

    /* Otra logica... */
} 

In the line: void *tmp = realloc(ptr, sz); My question is this:

If after this line I release the memory of ptr as follows:

free(ptr);

Will the tmp pointer still be valid and point to the new ^ memory address given by realloc ?

^: I say new because I don't know if realloc works like malloc to give memory addresses by resizing them.

Answer:

If after that line you release ptr , tmp will no longer be valid. Here's an example:

#include <stdlib.h>

int
main(int argc, char *argv[]) {
   int *ptr;
   int *tmp;

   ptr = malloc(128);
   tmp = realloc(ptr, 256);
   free(ptr);
   free(tmp);

   return 0;
}

When you run the code you get:

Error in `./test': double free or corruption (top): 0x00000000019cb010 

realloc works like malloc if ptr is NULL . If size is 0 then realloc works like free .

Here another example:

#include <stdlib.h>
#include <stdio.h>

int
main(int argc, char *argv[]) {
   int *ptr;
   int *tmp;

   ptr = malloc(128);
   tmp = realloc(ptr, 256);

   printf("%p == %p\n", ptr, tmp);

   free(ptr);

   return 0;
}

And you will see that both addresses are the same.

Scroll to Top