ProgrammingHardHCL · Tech Mahindra pattern
What happens when this runs?
What happens when this runs?
int *p = NULL;
printf("%d", *p);- A. 0, since dereferencing NULL always reads 0
- B. Undefined behaviour: dereferencing a null pointer
- C. Compile-time error: cannot dereference NULL
- D. It always crashes with a segmentation fault
Correct answer: B. Undefined behaviour: dereferencing a null pointer
Dereferencing a null pointer is undefined behaviour per the C standard. In practice it very often crashes (segfault) on common OSes because address 0 is unmapped, but the standard does not require a crash — it could also appear to 'succeed' and read garbage on some embedded or unusual platforms, so neither of the other options is guaranteed.
More C Programming questions
- 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)…
- What happens when this runs? c int arr[10]; for (int i = 0; i <= 10; i++) { arr[i] = i; } printf("done");