ProgrammingHardProduct company OA · GATE CS
After `int *q = realloc(p, 2 * n * sizeof *q);` succeeds (q is not NULL), where p pointed to n ints, which statement is true?
- A. The n new ints at the end are zero-initialised
- B. p and q always hold the same address
- C. p must still be freed separately from q
- D. The first n ints are preserved in q, and p must not be used any more because the block may have moved
Correct answer: D. The first n ints are preserved in q, and p must not be used any more because the block may have moved
realloc keeps the old contents up to the smaller size, but it may move the block, after which the old pointer is invalid; only q may be used and freed. The added part is uninitialised (unlike calloc), and freeing p as well would be a double free.
More C Programming questions
- With int i = 1, x; int a[5] = {0}; which of these statements have undefined behaviour? (i) i = i++ + 1; (ii) a[i] = i++; (iii) i = (i, i +…
- Which of the objects A to E have static storage duration (they live for the whole run of the program, in the data or BSS segment)? c int…
- What is printed? c int cmp(const void a, const void b) { return (const int )b - (const int )a; } int main(void) { int v[] = {4, 9, 1, 7}…
- What is printed? c printf("%d %d %d", atoi("42abc"), atoi(" -7x"), atoi("x9"));
- What is printed? c int a = 0, b = 0; int n = sscanf("12 abc 7", "%d %d", &a, &b); printf("%d %d %d", n, a, b);
- With 4-byte int, what is printed? c int p = (int[]){10, 20, 30}; p[1] += 5; printf("%d %zu", p[1] + p[2], sizeof((int[]){10, 20, 30}) /…