Step 1: Analyze memory allocation and initialization
The pointer ptr points to a new integer initialized with 10.
Step 2: Understand output before deletion
Dereferencing *ptr prints 10 before memory is deleted.
Final Answer:
10 -> Option B
Quick Check:
Dereference new int(10) = 10 [OK]
Hint: Dereference pointer before delete to see value [OK]
Common Mistakes:
Assuming output is 0 or garbage
Thinking delete affects output before cout
Confusing syntax causing compile error
4. Identify the error in the following code snippet:
int* arr = new int[5]; delete arr;
medium
A. Pointer arr is not initialized
B. Memory is not allocated properly
C. No error, code is correct
D. Should use delete[] instead of delete
Solution
Step 1: Check allocation type
Memory allocated with new[] must be deallocated with delete[].
Step 2: Identify mismatch in deallocation
Using delete instead of delete[] causes undefined behavior.
Final Answer:
Should use delete[] instead of delete -> Option D
Quick Check:
Array deallocation = delete[] [OK]
Hint: Match new[] with delete[] always [OK]
Common Mistakes:
Using delete for arrays
Ignoring pointer initialization
Assuming no error in mismatched delete
5. You want to allocate memory for an array of 10 integers and initialize all elements to zero. Which code snippet correctly does this and safely deallocates the memory?
hard
A. int* arr = new int[10](); delete[] arr;
B. int* arr = new int[10]; delete arr;
C. int* arr = (int*)malloc(10 * sizeof(int)); delete[] arr;
D. int* arr = new int(10); delete[] arr;
Solution
Step 1: Allocate and initialize array to zero
Using new int[10]() allocates an array of 10 integers and initializes all to zero.
Step 2: Properly deallocate array memory
Memory allocated with new[] must be freed with delete[] to avoid leaks or undefined behavior.
Final Answer:
int* arr = new int[10](); delete[] arr; -> Option A
Quick Check:
new[] with () + delete[] = safe zero-init array [OK]
Hint: Use new int[size]() and delete[] for arrays [OK]
Common Mistakes:
Using delete instead of delete[] for arrays
Mixing malloc/free with new/delete
Allocating single int instead of array
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.