Topic: Programming Concepts
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;
Answer: C. ptr[4]=0x16;
Explanation: The array is allocated with a size of 4, meaning the valid indices are 0, 1, 2, and 3. Accessing and writing to `ptr[4]` is an out-of-bounds memory access (buffer overflow). This invokes undefined behavior and can corrupt adjacent memory, leading to an immediate or subsequent program crash.