Question: How to deallocate dynamically allocate memory without using “free()” function.
Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of “realloc()” from “stdlib.h”
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.
Check the leak summary with valgrind tool. It shows memory leak of 10 bytes, which is highlighed in red colour.
[narendra@ubuntu]$ 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. [narendra@ubuntu]$
Let us modify the above code.
Check the valgrind’s output. It shows no memory leaks are possible, highlighted in red color.
[narendra@ubuntu]$ 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. [narendra@ubuntu]$
This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Dangling, Void , Null and Wild Pointers
- C Program to print numbers from 1 to N without using semicolon?
- Enumeration (or enum) in C
- How to dynamically allocate a 2D array in C?
- Commonly Asked C Programming Interview Questions | Set 1
- To find sum of two numbers without using any operator
- Catch block and type conversion in C++
- Memory Layout of C Programs
- How does free() know the size of memory to be deallocated?
- fseek() vs rewind() in C
- Use of realloc()
- calloc() versus malloc()
- What is Memory Leak? How can we avoid?
- Understanding "extern" keyword in C