LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Find the Error · Question 5

Double free after copying a struct with a pointer Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below has a problem. Which statement correctly describes it?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links