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
476 views
in Technique[技术] by (71.8m points)

c - why using sizeof in malloc?

When executing this code on IDEONE:

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

struct A{
    int x;
    char c;
};

struct B{
    int y;
};

int main(void) {
    // your code goes here
    struct A* pa = malloc(sizeof(struct B));
    printf("%d
",sizeof(*pa));
    pa = malloc(sizeof(int));
    printf("%d
",sizeof(*pa));
    pa = malloc(sizeof(char));
    printf("%d
",sizeof(*pa));
    pa = malloc(0);
    printf("%d
",sizeof(*pa));
    return 0;
}

I got:

8
8
8
8

I'm guessing that since pa is of type struct A * and struct A is 8 bytes long, then malloc is allocating 8 bytes, as it should, but if so, why use sizeof?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

sizeof doesn't return the size of the memory block that was allocated (C does NOT have a standard way to get that information); it returns the size of the operand based on the operand's type. Since your pointer is of type struct A*, the sizeof operand is of type struct A, so sizeof always returns 8.

So, even if you allocate 1 byte for a 10000 byte structure, you will still see sizeof return 10000.

If you don't allocate enough memory for that object (e.g. because sizeof(int) < sizeof(struct A)) but you try to use the object anyway, you'll encounter undefined behaviour - your program is no longer well defined and anything could happen (nothing, crashing, memory corruption, hackers owning your computer).


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

...