ProgrammingHardTCS NQT · Infosys pattern
What happens when this runs?
What happens when this runs?
struct Point { int x, y; };
struct Point *p = malloc(sizeof(struct Point));
printf("%d", p->x);- A. 0, since malloc zero-initialises memory
- B. Undefined behaviour: malloc does not initialise memory, so p->x holds an indeterminate value
- C. Compile-time error: p->x is used before being assigned
- D. Always the same garbage value across all runs and systems
Correct answer: B. Undefined behaviour: malloc does not initialise memory, so p->x holds an indeterminate value
malloc only reserves raw memory; it does NOT clear or initialise it (unlike calloc, which does zero-fill). Reading p->x before explicitly assigning it is reading an indeterminate value, which is undefined behaviour — it is a common and dangerous mistake to assume malloc'd memory starts at zero.
More C Programming questions
- What happens when this runs? c char concat(const char a, const char b) { char result[100]; strcpy(result, a); strcat(result, b); return…
- What is printed? c int a = 5, b = 2, c = 3; int result = a > b > c; printf("%d", result);
- What is printed? c int a = 1, b = 2, c = 3; int result = a == 1 && b == 2 || c == 100; printf("%d", result);
- What is printed? c int a = 4; int b = ~a + 1; printf("%d %d", b, -a);
- What is printed? c int x = 1, y = 2, z = 3; int result = x < y < z; printf("%d", result);
- What is printed? c int a = 5; int b = a++ + ++a; printf("%d %d", a, b);