ProgrammingHardWipro · Cognizant pattern
What happens when this runs?
What happens when this runs?
int *p = malloc(sizeof(int) * 5);
if (p) {
for (int i = 0; i < 5; i++) p[i] = i;
}
int *q = realloc(p, sizeof(int) * 10);
if (q) {
for (int i = 5; i < 10; i++) q[i] = i;
printf("%d %d", q[0], q[9]);
}
free(q);- A. 0 9
- B. Undefined behaviour: p is used after realloc without checking if q == p
- C. 0 0
- D. Compile-time error: realloc cannot grow an allocation
Correct answer: A. 0 9
realloc either extends the existing block in place or allocates a new block and copies the old contents over (then frees the old one), always returning the valid pointer to use going forward; the first 5 ints (0..4) are preserved by realloc's copy, and the code correctly uses q (not the now-possibly-stale p) afterward. q[0]=0 (preserved), q[9]=9 (newly written).
More C Programming questions
- Assume 32-bit int. What is printed? c int arr[5] = {1, 2, 3, 4, 5}; int p = arr; int sum1 = arr[2] + (arr + 2); int sum2 = (p + 2) + p[2]…
- What is printed? c #define SIGN(x) ((x) > 0 ? 1 : (x) < 0 ? -1 : 0) int main(void) { int values[3] = {-5, 0, 7}; for (int i = 0; i < 3…
- Assume a 64-bit LP64 ABI. What is printed? c struct Student { char name[10]; int marks[3]; }; struct Student s = {"Bob", {80, 90, 70}}…
- Assume 32-bit int. What is printed? c int x = 1; int y = 2; int z = 3; int result = x + y == z; printf("%d", result);
- What happens when this runs? c int divide(int result, int a, int b) { if (b == 0) return -1; result = a / b; return 0; } int main(void) {…
- Assume 32-bit int. What is printed? c int x = 3; int result = x++ + x++ - x++; printf("%d", result); printf(" valid: %s", "no, undefined…