ProgrammingHardHCL · Tech Mahindra pattern
What happens?
What happens?
int arr[3] = {1, 2, 3};
int *p = arr;
p += 10;
*p = 99;
printf("done");- A. Compilation error: pointer arithmetic cannot exceed array bounds
- B. Undefined behaviour: p is advanced 10 elements past a 3-element array and then dereferenced for a write, far outside any valid object
- C. It prints done and silently does nothing else
- D. It always crashes with a clear segmentation fault message
Correct answer: B. Undefined behaviour: p is advanced 10 elements past a 3-element array and then dereferenced for a write, far outside any valid object
Advancing a pointer more than one-past-the-end of its array is already undefined behaviour even before dereferencing; writing through it (*p = 99) compounds this into a genuinely undefined memory write, which might corrupt unrelated data, might crash, or might appear to 'work' — none of which is guaranteed or safe.
More C Programming questions
- What happens? c int compare(const void a, const void b) { return (int )a - (int )b; } int main(void) { int arr[] = {5, 2, 8, 1, 9}…
- Assume 32-bit int. What is printed? c unsigned int a = 0; a--; printf("%u", a);
- Assume 32-bit int. What is printed? c int flags = 0b1010; int mask = 0b0110; printf("%d %d", flags & mask, flags | mask);
- Assume 32-bit int. What is printed? c int x = 100; int y = x << 1; int z = x >> 1; printf("%d %d", y, z);
- Assume 32-bit int. What is printed? c int a = 12, b = 10; int x = a ^ b; int y = x ^ b; int z = x ^ a; printf("%d %d", y, z);
- Assume 32-bit int. What is printed? c int x = 0xFF; int y = x & 0x0F; int z = (x >> 4) & 0x0F; printf("%d %d", y, z);