ProgrammingHardWipro · Cognizant pattern
What happens when this runs?
What happens when this runs?
int a[5] = {1, 2, 3, 4, 5};
a[5] = 100;
printf("%d", a[5]);- A. 100, since C automatically grows arrays
- B. Undefined behaviour: a[5] is one past the valid index range of a 5-element array
- C. Compile-time error: array index 5 is out of bounds
- D. 0, since out-of-bounds writes are silently ignored
Correct answer: B. Undefined behaviour: a[5] is one past the valid index range of a 5-element array
a has valid indices 0..4; a[5] accesses memory outside the array entirely. C performs no bounds checking, so both the write and the read are undefined behaviour — it may silently 'work' by corrupting adjacent memory, or crash, or do something else entirely, with no guarantee either way.
More C Programming questions
- What happens when this runs? c int p = NULL; printf("%d", p);
- What happens when this runs? c int p = malloc(sizeof(int)); free(p); printf("%d", p);
- What happens when this runs? c int f(void) { int x = 5; return x; } int g(void) { int y = 10; return &y; } int main(void) { int p = g()…
- What happens when this runs? c char buf[5]; strcpy(buf, "hello world"); printf("%s", buf);
- What happens when this runs? c int divide(int a, int b) { return a / b; } int main(void) { printf("%d", divide(10, 0)); }
- What happens when this runs? c int p = (int )malloc(3 sizeof(int)); if (p == NULL) { return 1; } p[0] = 1; p[1] = 2; p[2] = 3; free(p)…