0
0
C++programming~20 mins

Memory allocation and deallocation in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Memory Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of dynamic memory allocation with pointers
What is the output of the following C++ code?
C++
#include <iostream>
int main() {
    int* p = new int(10);
    std::cout << *p << std::endl;
    delete p;
    return 0;
}
A0
BCompilation error
CRuntime error
D10
Attempts:
2 left
💡 Hint
Remember that new allocates memory and initializes the value.
Predict Output
intermediate
2:00remaining
Output after deleting and accessing pointer
What happens when you run this C++ code?
C++
#include <iostream>
int main() {
    int* p = new int(5);
    delete p;
    std::cout << *p << std::endl;
    return 0;
}
AUndefined behavior (may print garbage or crash)
B5
CCompilation error
D0
Attempts:
2 left
💡 Hint
Accessing memory after delete is unsafe.
🧠 Conceptual
advanced
2:00remaining
Correct use of delete[] for arrays
Which option correctly deallocates the dynamically allocated array in C++?
Aint* arr = new int[5]; delete arr;
Bint* arr = new int[5]; free(arr);
Cint* arr = new int[5]; delete[] arr;
Dint* arr = new int[5]; delete arr[0];
Attempts:
2 left
💡 Hint
Arrays allocated with new[] must be deallocated with delete[].
Predict Output
advanced
2:00remaining
Output of double delete error
What error or output occurs when running this code?
C++
#include <iostream>
int main() {
    int* p = new int(7);
    delete p;
    delete p;
    std::cout << "Done" << std::endl;
    return 0;
}
ARuntime error (double free or corruption)
B7
CCompilation error
DDone
Attempts:
2 left
💡 Hint
Deleting the same pointer twice causes a runtime error.
🧠 Conceptual
expert
3:00remaining
Memory leak detection in C++ code
Which option describes the memory leak in the following code snippet?
C++
void foo() {
    int* p = new int[10];
    p = new int[20];
    delete[] p;
}
ANo memory leak; all allocated memory is freed.
BMemory leak because the first allocated array is lost without delete.
CMemory leak because delete[] is used incorrectly.
DMemory leak because p is deleted twice.
Attempts:
2 left
💡 Hint
Reassigning pointer without deleting old memory causes leak.