Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

c - why does malloc(sizeof(pointer)) work?

This following code works fine:

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

int main()
{
    struct node{
        int a, b, c, d, e;
    };
    struct node *ptr = NULL;
    printf("Size of pointer ptr is %lu bytes
",sizeof (ptr));
    printf("Size of struct node is %lu bytes
",sizeof (struct node));
    ptr = (struct node*)malloc(sizeof (ptr));               //Line 1
//    ptr = (struct node*)malloc(sizeof (struct node));    //Line 2

    ptr->a = 1; ptr->b = 2; ptr->c = 3; ptr->d = 4; ptr->e = 5;
    printf("a: %d, b: %d, c: %d, d: %d, e: %d
",
            ptr->a,ptr->b,ptr->c,ptr->d,ptr->e);
    return 0;
}

When complied as:

gcc -Wall file.c

My question is: why is this fine?

malloc allocates the number of bytes which are specified in it's argument. Here sizeof ptr is 8 bytes on my 64-bit linux machine. I thought malloc will provide 8 bytes but then how is it accessing all the variables a,b,c,d,e? Is it with gcc only or am I missing something with standard C?

As far as I know "Line 2" should be there instead of "Line 1" but either of the line works fine. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have undefined behavior here.

malloc will allocate 8 bytes (as you say), but this cast is "bad":

ptr = (struct node*)malloc(sizeof (ptr));

After this line, ptr will point to a memory block, which has only 8 allocated bytes, the rest are some "random" bytes. So, making

ptr->a = 1; ptr->b = 2; ptr->c = 3; ptr->d = 4; ptr->e = 5;

you actually change some memory, not only the allocated by malloc.

In other words, you are rewriting memory, you're not supposed to touch.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...