![]() |
VOOZH | about |
Memory leaks are a common and serious problem in C++ programming. They occur when dynamically allocated memory using operators like new or functions like malloc from the heap is not properly deallocated using delete or free, resulting in slow system resource utilization, degraded performance, and potential program crashes.
Detecting memory leaks in C++ can be challenging due to the lack of automatic memory management. However, several strategies and tools can help detect and prevent memory leaks:
Following are the tools that can be used to detect memory leaks in C++:
Let us consider the following program where we have dynamically allocated an array and did not freed it's memory which leads to memory leak. We will detect for memory leaks in the following program with the help of valgrind.
memory_leak.cpp
To detect memory leaks using the valgrind tool in C++ for the above program, follow the below steps:
1. Compile the program file using the below command in your terminal:
g++ -g -o memory_leak memory_leak.cpp2. Now run the valgrind tool to detect the memory leaks using the following command:
valgrind --leak-check=full ./memory_leakFollowing output will be generated by Valgrind in the terminal describing all the details about the memory leaks:
Output
==12345== Memcheck, a memory error detector
==12345== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==12345== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==12345== Command: ./leaky_program
==12345==
==12345==
==12345== HEAP SUMMARY:
==12345== in use at exit: 400 bytes in 1 blocks
==12345== total heap usage: 1 allocs, 0 frees, 400 bytes allocated
==12345==
==12345== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==12345== at 0x4C2AB80: operator new[](unsigned long) (vg_replace_malloc.c:423)
==12345== by 0x1091A9: createMemoryLeak() (leaky_program.cpp:7)
==12345== by 0x1091BF: main (leaky_program.cpp:11)
==12345==
==12345== LEAK SUMMARY:
==12345== definitely lost: 400 bytes in 1 blocks
==12345== indirectly lost: 0 bytes in 0 blocks
==12345== possibly lost: 0 bytes in 0 blocks
==12345== still reachable: 0 bytes in 0 blocks
==12345== suppressed: 0 bytes in 0 blocks
==12345==
==12345== For counts of detected and suppressed errors, rerun with: -v
==12345== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)