Consider the following C++ code. What will it print?
#include <iostream> int main() { int* ptr = new int(10); ptr = new int(20); std::cout << *ptr << std::endl; return 0; }
Think about what happens to the first allocated memory when the pointer is reassigned.
The pointer ptr is first assigned to a new int with value 10. Then it is reassigned to a new int with value 20 without deleting the first allocation. The output prints the value pointed by ptr, which is 20. However, the first allocated memory is leaked because it was never freed.
Analyze this C++ code snippet. What error will it cause when run?
#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; }
Think about the lifetime of local variables and what happens when you return their address.
The function returns the address of a local array which is destroyed when the function ends. Accessing this memory leads to undefined behavior because the pointer points to invalid memory.
Which line causes a memory leak in the following C++ code?
#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; }
Consider what happens to the first allocated array when data is reassigned.
The first allocated array of 10 ints is never deleted before data is reassigned to a new array of 5 ints. This causes the first allocation to leak.
Which of the following C++ code snippets will cause undefined behavior related to memory management?
Think about the correct way to delete memory allocated with new[].
Memory allocated with new[] must be freed with delete[]. Using delete on an array causes undefined behavior.
Analyze the following C++ program. How many memory leaks occur when it runs?
#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; }
Count how many new allocations are made and how many delete calls are missing.
The program creates 3 nodes with new but never deletes any of them. This causes 3 memory leaks.