LearnFrenzy
Sign in Take a free test

Typedef · Find the Error · Question 8

A pointer hidden behind a typedef leads to a double free Answer, explanation & discussion

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

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

main.c
#include <stdlib.h>

typedef int *Buffer;          /* looks like a value type, but it is a pointer */

int main(void) {
    Buffer a = malloc(4 * sizeof(int));
    Buffer b = a;             /* the reader thinks: "a copy" */
    free(a);
    free(b);
    return 0;
}
  • A malloc() cannot return a Buffer
  • B Buffer hides a pointer, so b = a copies the address, not the data; the same block is freed twice Correct
  • C free() needs a cast
  • D There is no bug
Correct Answer: Option B

Because the typedef hides the *, the assignment looks like copying a value. Avoid pointer typedefs for owned memory, so every * reminds the reader who must free what.

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