0
0
C++programming~20 mins

Memory leak concept in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Memory Leak Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this C++ code snippet?

Consider the following C++ code. What will it print?

C++
#include <iostream>

int main() {
    int* ptr = new int(10);
    ptr = new int(20);
    std::cout << *ptr << std::endl;
    return 0;
}
A10
B20
CCompilation error
DUndefined behavior (possible crash)
Attempts:
2 left
💡 Hint

Think about what happens to the first allocated memory when the pointer is reassigned.

Predict Output
intermediate
2:00remaining
What error does this code cause?

Analyze this C++ code snippet. What error will it cause when run?

C++
#include <iostream>

int* createArray() {
    int arr[5] = {1,2,3,4,5};
    return arr;
}

int main() {
    int* p = createArray();
    std::cout << p[0] << std::endl;
    return 0;
}
ANo error, prints 1
BCompilation error: returning address of local variable
CRuntime error: segmentation fault
DUndefined behavior: accessing invalid memory
Attempts:
2 left
💡 Hint

Think about the lifetime of local variables and what happens when you return their address.

🔧 Debug
advanced
2:00remaining
Identify the memory leak in this code

Which line causes a memory leak in the following C++ code?

C++
#include <iostream>

void process() {
    int* data = new int[10];
    for (int i = 0; i < 10; ++i) {
        data[i] = i * 2;
    }
    if (data[0] < 5) {
        data = new int[5];
    }
    delete[] data;
}

int main() {
    process();
    return 0;
}
ALine: data = new int[5];
BLine: int* data = new int[10];
CLine: delete[] data;
DNo memory leak
Attempts:
2 left
💡 Hint

Consider what happens to the first allocated array when data is reassigned.

📝 Syntax
advanced
2:00remaining
Which option causes undefined behavior?

Which of the following C++ code snippets will cause undefined behavior related to memory management?

Aint* p = new int[5]; delete p;
Bint* p = new int[5]; delete[] p;
Cint* p = new int(5); delete p;
Dint* p = nullptr; delete p;
Attempts:
2 left
💡 Hint

Think about the correct way to delete memory allocated with new[].

🚀 Application
expert
3:00remaining
How many memory leaks occur in this program?

Analyze the following C++ program. How many memory leaks occur when it runs?

C++
#include <iostream>

class Node {
public:
    int value;
    Node* next;
    Node(int v) : value(v), next(nullptr) {}
};

int main() {
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);

    Node* temp = head;
    while (temp != nullptr) {
        temp = temp->next;
    }

    // No delete calls
    return 0;
}
A2
B1
C3
D0
Attempts:
2 left
💡 Hint

Count how many new allocations are made and how many delete calls are missing.