In C programming, you often malloc function to create chunk of memory for making our program to execute. And, you use the free function to reclaim the allocated memory and making it available to the other programs. But, this is a very tricky questions mostly asked in any interviews for the C Programming, that how to achieve that same thing without using free() function?

Mostly during programming you shall use the malloc and free functions but there is another function that can do the same thing. That is realloc() function. Lets look that how it works and how you can validate it yourself.

The function realloc() can be used to deallocate previously allocated memory. The function declaration “realloc()” is done  from “stdlib.h”.

1
   void *realloc(void *ptr, size_t size);  

If “size” is zero, then call to realloc is equivalent to “free(ptr)”. And if “ptr” is NULL and size is non-zero then call to realloc is equivalent to “malloc(size)”.

Let us check with simple example.

1
2
3
4
5
6
7
8
9
10
/* code with memory leak */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int <em>ptr = (int</em>)malloc(10);

return 0;
}

Now you can check the leak summary with valgrind tool. It shows memory leak of 10 bytes, which is highlighed in red colour.

[[email protected]]$ valgrind –leak-check=full ./free
  ==1238== LEAK SUMMARY:
  ==1238==    definitely lost: 10 bytes in 1 blocks.
  ==1238==      possibly lost: 0 bytes in 0 blocks.
  ==1238==    still reachable: 0 bytes in 0 blocks.
  ==1238==         suppressed: 0 bytes in 0 blocks.
[[email protected]]$

Let us change the above code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</div>
<div id="highlighter_777482" class="syntaxhighlighter nogutter  c">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main(void)
{
int *ptr = (int*) malloc(10);

/* we are calling realloc with size = 0 */
realloc(ptr, 0);


return 0;
}</div>
<div>

Now again check the valgrind tools output. You can see no memory leaks are possible, highlighted in red color.

  [[email protected]]$ valgrind –leak-check=full ./a.out
  ==1435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
  ==1435== malloc/free: in use at exit: 0 bytes in 0 blocks.
  ==1435== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.
  ==1435== For counts of detected errors, rerun with: -v
  ==1435== All heap blocks were freed — no leaks are possible.
  [[email protected]]$

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please share with your friends and others.

LEAVE A REPLY

Please enter your comment!
Please enter your name here