0
0
C++programming~20 mins

new operator in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of new operator
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of dynamic array allocation
What is the output of this C++ code snippet?
C++
#include <iostream>
int main() {
    int* arr = new int[3]{1, 2, 3};
    std::cout << arr[1] << std::endl;
    delete[] arr;
    return 0;
}
A3
B1
C2
DCompilation error
Attempts:
2 left
💡 Hint
Remember that array indexing starts at 0.
Predict Output
intermediate
2:00remaining
Output of new operator with class object
What will this program print?
C++
#include <iostream>
class Box {
public:
    int length;
    Box(int l) : length(l) {}
};
int main() {
    Box* b = new Box(10);
    std::cout << b->length << std::endl;
    delete b;
    return 0;
}
ARuntime error
B0
CCompilation error
D10
Attempts:
2 left
💡 Hint
Check how the constructor initializes the length.
Predict Output
advanced
2:00remaining
Output when forgetting to delete dynamic memory
What is the output of this program?
C++
#include <iostream>
int main() {
    int* p = new int(5);
    *p = 10;
    std::cout << *p << std::endl;
    // no delete called
    return 0;
}
A10
B5
CCompilation error
DRuntime error due to memory leak
Attempts:
2 left
💡 Hint
The program prints the value pointed by p before exiting.
Predict Output
advanced
2:00remaining
Output of new operator with placement new
What will this program output?
C++
#include <iostream>
#include <new>
int main() {
    char buffer[sizeof(int)];
    int* p = new(buffer) int(42);
    std::cout << *p << std::endl;
    p->~int();
    return 0;
}
A0
B42
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Placement new constructs an object in pre-allocated memory.
🧠 Conceptual
expert
2:00remaining
What error occurs when deleting non-dynamically allocated memory?
Consider this code snippet: int x = 5; int* p = &x; delete p; What happens when this code runs?
AUndefined behavior, likely runtime error
BDeletes x safely, no error
CCompilation error because delete cannot be used on stack variables
DMemory leak occurs
Attempts:
2 left
💡 Hint
delete should only be used on memory allocated with new.