LearnFrenzy
Sign in Take a free test

Memory Allocation · Find the Error · Question 8

Bug: malloc(sizeof p) instead of malloc(sizeof *p) Answer, explanation & discussion

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

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

main.c
#include <stdio.h>
#include <stdlib.h>

struct record {
    char name[24];
    int score;
};

int main(void) {
    struct record *r = malloc(sizeof r);
    if (r == NULL)
        return 1;
    r->score = 90;
    printf("%d\n", r->score);
    free(r);
    return 0;
}
  • A struct record cannot be allocated
  • B sizeof r is the pointer size (8), not the 28-byte struct, so r->score is outside the block Correct
  • C r->score should be r.score
  • D There is no problem
Correct Answer: Option B

One missing *: sizeof r measures the pointer. Writing score at offset 24 lands past the 8-byte block. Write malloc(sizeof *r).

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