ProgrammingVery hard
Which realloc pattern does not leak memory or lose the original block if the reallocation fails?
- A. p = realloc(p, newsize); if (!p) exit(1);
- B. int *t = realloc(p, newsize); if (!t) { /* p still valid */ } else p = t;
- C. free(p); p = malloc(newsize);
- D. p = realloc(p, newsize); if (p == NULL) free(p);
Correct answer: B. int *t = realloc(p, newsize); if (!t) { /* p still valid */ } else p = t;
realloc returns NULL on failure and leaves the old block valid, so assigning the result straight back to p loses the pointer. The temporary keeps the old block reachable.
More C Programming questions
- A dynamic array doubles its capacity whenever it is full. Pushing N = 10^6 values costs about how many element copies in total?
- A function returns a pointer to a node created with malloc inside it. Which description is correct?
- Which statement about calloc(n, size) is guaranteed by the C standard?
- A program calls free(p) and then reads p->v in the next line. What is the correct description?
- A hash chain delete on a singly linked bucket list is written with a pointer-to-pointer. Which description is the advantage?
- Building a list from n values by inserting each new node at the head is O(1) per insert. What is the order of the values when read from…