I just wrote a code in C++ which does some string manipulation, but when I ran valgrind over, it shows some possible memory leaks. Debugging the code to granular level I wrote a simple C++ program looking like:
#include<iostream> #include<cstdlib> using namespace std; int main() { std::string myname("Is there any leaks"); exit(0); }
and running valgrind over it I got:
==20943== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 26 from 1) ==20943== malloc/free: in use at exit: 360,645 bytes in 12,854 blocks. ==20943== malloc/free: 65,451 allocs, 52,597 frees, 2,186,968 bytes allocated. ==20943== For counts of detected errors, rerun with: -v ==20943== searching for pointers to 12,854 not-freed blocks. ==20943== checked 424,628 bytes. ==20943== ==20943== LEAK SUMMARY: ==20943== definitely lost: 0 bytes in 0 blocks. ==20943== possibly lost: 917 bytes in 6 blocks. ==20943== still reachable: 359,728 bytes in 12,848 blocks. ==20943== suppressed: 0 bytes in 0 blocks. ==20943== Reachable blocks (those to which a pointer was found) are not shown. ==20943== To see them, rerun with: --show-reachable=yes
Then it struck me that we have forcefully exited (which i performed in my original C++ code as well). Now the problem is that I want to exit from the program as my previous old code waits for the exit status of the new code. For e.g binary a.out waits for the exit status of b.out. Is there any way to avoid the memory leaks, or should i really worry about the memory leaks as the program is already exiting at that point.
This also raise another question for me, is such a code harmful?
#include<stdio.h> #include<cstdlib> int main() { char *p=(char *)malloc(sizeof(char)*1000); exit(0); }
In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.
Generally, a memory leak occurs in C/C++ programming when the pointer is lost its original allocated value. It becomes the cause of the memory leak because the allocated object becomes unreachable and cannot be deallocated.
Answer: Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
Use return 0;
instead of exit(0);
at the end of main
. The use of exit
circumvents the execution of the destructors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With