Behaviuor of realloc()

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi

According to libc, realloc() will, if not succeeding in reallocating memory, return NULL. Question is, what will happen with the previous allocated block? I see that the content remains unaltered, what realloc concerns according to libc description, but is it also freed?.

If not one would possible have a memory leak if not using an intermediate pointer when reallocating since the pointer reallocated suddenly is a NULL pointer.

int* pP = malloc(some_size);

pP = realloc((void*)pP, (some_size + some_extra_size));

if (pP == NULL)
  //pP is now destroyed and we have loost our handle to the memory block allocated and thus we are unable to free prev. allocated space if realloc does not do it 

As I could use an intermediate pointer the issue is not big, but the methode used by realloc() in most non-avr libs is that realloc uses errno and sets it to [ENOMEM] which may be checked. avr-libc does not mention this at all (1.6.2 on 16 Jun 2010.).

What would be the safe way of using realloc in avr-libc.

Regards
Vidar (Z)

----------------------------------------------------------

"The fool wonders, the wise man asks"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

http://www.cplusplus.com/referen...

Quote:
If the function failed to allocate the requested block of memory, a NULL pointer is returned, and the memory block pointed to by argument ptr is left unchanged.

Also see:

http://en.wikipedia.org/wiki/Mal...

which mentions the potential for a memory leak if you try to re-use the same pointer.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

With other words, intermediate pointer is the way to go.

Thanks

Regards
Vidar (Z)

----------------------------------------------------------

"The fool wonders, the wise man asks"