Question 9
Back to Exercise
What is the output of the following C program on a 64-bit system?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *s = malloc(16);
if (s == NULL)
return 1;
strcpy(s, "shrinking");
char *t = realloc(s, 6);
if (t == NULL) {
free(s);
return 1;
}
t[5] = '\0';
puts(t);
free(t);
return 0;
}
- A shrin Correct
- B shrink
- C shrinking
- D garbage
Correct Answer: Option A
Shrinking keeps the first 6 bytes ("shrink"). The old terminator was cut off, so the program writes a new one at index 5, leaving "shrin". Always re-terminate after shrinking a string.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!