I'm developing an application that requires to put/free and re-allocate memory in a somewhat excessive way, but I have a doubt regarding the use of the function realloc(void *, size_t)
, 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... */
}
On the line: void *tmp = realloc(ptr, sz);
my question is the following:
If after this line I release the memory ptr
as follows:
free(ptr);
Will the pointer tmp
still be valid and point to the new ^ memory address given by realloc
?
^: I say new because I don't know if it realloc
works malloc
to give memory addresses by resizing them.
If after that line you release
ptr
,tmp
it will no longer be valid. Here's an example:When you run the code you get:
realloc
it works asmalloc
if itptr
isNULL
. Ifsize
it is0
then itrealloc
works likefree
.Here another example:
And you will see that both addresses are the same.
The functions to work with dynamic memory are:
malloc
: This function allows us to reserve a memory area of the size we want.calloc
: Similar tomalloc
. In addition to reserving memory, it initializes all bytes to 0.realloc
: Attempts to relocate the data to a different memory zone according to the new requirements (these new requirements may imply a larger or smaller zone).free
: This function releases the memory reserved with any of the above three methods.A possible example of the implementation of
realloc
could be the following:Namely:
That said, if you do the following:
The result will be one of the following possibilities:
tmp==NULL
, you will be losing the original memory with no way back.tmp!=NULL
, you will be trying to free a memory zone that is already freed and that usually causes the application to close.And none of these options seem to be desirable.
What you have to do is reserve
free
for when you really no longer need the memory you are using. The following example has no memory leaks:And it does the following: