w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Free() function in C does not produce any error on freeing realloced data, but does not free the actual content. What can be the reason?

In your program you pass into your program two pointers related to the memory you allocated. One is the address of your buffer pointer which you allocated. The other is a pointer into the buffer called freeCh.

In your recursive function, you latter reallocate onto *buffer. However, a reallocation may return a pointer different from the one that was originally allocated. When this happens, freeCh is no longer pointing to a valid memory location. And then, you code modifies the memory at freeCh, which is now freed memory.

Incidentally, when realloc() returns NULL, it has not freed the original pointer that you attempted to reallocate. So, you should not directly overwrite the pointer that you are reallocating with the return value of realloc(). You should use a temporary variable, and then test if realloc() returned a valid pointer. Assign this value to the pointer you reallocated only if realloc() succeeded.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.