ProgrammingModerateProduct company OA
Why is the line `p = realloc(p, 2 * n * sizeof *p);` considered unsafe?
- A. realloc never moves the block, so the extra space may overwrite other data
- B. If realloc fails it returns NULL into p, so the still-allocated old block can no longer be reached or freed
- C. sizeof *p is evaluated after realloc returns, so the size is undefined
- D. realloc always frees the old block, so p dangles afterwards
Correct answer: B. If realloc fails it returns NULL into p, so the still-allocated old block can no longer be reached or freed
On failure realloc returns NULL but keeps the old block alive; overwriting p with NULL leaks it and loses the data. The fix is tmp = realloc(p, …); if (tmp) p = tmp;. sizeof does not evaluate its operand, and realloc may move the block when it must.
More C Programming questions
- Given char s[] = "ab"; and the declarations below, for which of p1 to p4 does the statement p = 'x'; compile? c typedef char PC; const PC…
- Assume 32-bit unsigned int. What is printed? c unsigned int u = 1u << 31; printf("%u %u", u >> 31, (u >> 30) | (u >> 28 & 1));
- What is printed? c int x = 5, s = 0; switch (x) { default: s += 1; case 1: s += 10; case 2: s += 100; break; case 3: s += 1000; }…
- What is f in the declaration below? c int ((f)(int))[3];
- What is printed? c char s[10] = "abc"; char t[] = "xyz"; strncat(s, t, 2); printf("%s %zu %d", s, strlen(s), strncmp(s, "abcx", 4) == 0);
- What is printed? c char s[] = {"alpha", "beta", "gamma", "delta"}; char p = s; p += 2; printf("%c ", p); printf("%c ", ((p - 1) + 2))…