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”.
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.
/* code with memory leak */
int <em>ptr = (int</em>)malloc(10);
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.
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.