Question 5
Back to Exercise
The program below has a problem. Which statement correctly describes it?
#include <stdlib.h>
struct buffer {
char *data;
};
int main(void) {
struct buffer a = {malloc(16)};
struct buffer b = a;
free(a.data);
free(b.data);
return 0;
}
- A malloc() cannot be called in an initializer
- B b.data must be set to NULL first
- C There is no error
- D b = a copies only the pointer, so the same block is freed twice Correct
Correct Answer: Option D
Struct assignment is a shallow copy: a.data and b.data hold the same address. Freeing it twice is undefined behaviour (a sanitizer reports "double free"). Give one struct ownership, or write a deep-copy function.
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!