Consider following C++ snippet, which allocates memory?int *ptr; ptr = new int…
2025
Consider following C++ snippet, which allocates memory?
int *ptr;
ptr = new int [4];
Which of the following statements may make the program crash when executed subsequently?
- A.
ptr++;
- B.
ptr += 3;
- C.
ptr[4] = 0x16;
- D.
ptr = null;
Attempted by 92 students.
Show answer & explanation
Correct answer: C
The correct answer is Option C. In the provided snippet, `new int[4]` allocates an array of four integers with valid indices 0, 1, 2, and 3. Accessing `ptr[4]` attempts to read or write memory at index 4, which is out of bounds. This violates the allocated memory region, leading to undefined behavior that frequently causes a program crash or data corruption. While pointer arithmetic like `ptr++` (Option A) or `ptr += 3` (Option B) moves the pointer, they do not inherently crash unless dereferenced outside bounds. Assigning `ptr = null` (Option D) is a safe operation that simply updates the pointer value. Therefore, directly accessing invalid memory via `ptr[4]` is the specific action that triggers a crash.