Memory Leaks

Detecting and preventing memory leaks

Interview Relevant: Debugging skills

Memory Leaks

Memory leaks occur when allocated memory is not freed.

Code Examples

Identifying and preventing memory leaks.

cpp
1// Memory leak example
2void leak() {
3    int* p = new int[100];
4    // Forgot delete[] - memory leaked!
5}
6
7// Exception-unsafe code
8void unsafe() {
9    int* p = new int[100];
10    doSomething();  // If this throws, memory leaks!
11    delete[] p;
12}
13
14// Prevention: use smart pointers
15void safe() {
16    auto p = make_unique<int[]>(100);
17    doSomething();  // If throws, unique_ptr cleans up
18}  // Automatically freed
19
20// Prevention: RAII wrapper
21class ArrayWrapper {
22    int* data;
23public:
24    ArrayWrapper(int size) : data(new int[size]) {}
25    ~ArrayWrapper() { delete[] data; }
26};
27
28// Detection tools:
29// - Valgrind (Linux)
30// - AddressSanitizer (-fsanitize=address)
31// - Visual Studio Memory Profiler

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In