Can realloc potentially cause a memory leak?

J

Jeff Rodriguez

If you realloc, and the new memory has a different address, what happens at the
old address? Is that memory basically free()'d, or do you need to keep track of
address changes and manually free() ?

Jeff
 
A

Artie Gold

Jeff said:
If you realloc, and the new memory has a different address, what happens
at the old address? Is that memory basically free()'d, or do you need to
keep track of address changes and manually free() ?
It is free()-ed.

HTH,
--ag
 
M

Morris Dovey

Jeff said:
If you realloc, and the new memory has a different address, what happens
at the old address? Is that memory basically free()'d, or do you need to
keep track of address changes and manually free() ?

Jeff...

It doesn't cause a memory leak. It works to consider that memory
freed for re-use; but the actual (under the covers) disposition
is up to the implementation.
 
M

Mac

If you realloc, and the new memory has a different address, what happens at the
old address? Is that memory basically free()'d, or do you need to keep track of
address changes and manually free() ?

Jeff

In the case you seem to be discussing, the memory is effectively freed,
and you MUST not free it.

Misuse of realloc CAN cause a memory leak, but only when allocation fails.

Here's an example:


#include <stdlib.h>
....
char *foo;
int buf_size = 1;
....

foo = malloc(buf_size);
....

foo = realloc(foo, buf_size *= 2);

Here, if realloc fails, the memory previously pointed to by foo will still
be claimed, but you will have lost your only pointer to it, because
realloc returns NULL on failure. This is a memory leak.

HTH

Mac
--
 
D

Derk Gwen

# If you realloc, and the new memory has a different address, what happens at the
# old address? Is that memory basically free()'d, or do you need to keep track of
# address changes and manually free() ?

If the returned address is different from the input address, the input
address is no longer valid, as if it were passed to free; it can no longer
be safely freed, reallocked, or used to access memory. What actually happens
is implementation dependent.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top