问题
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\n",sizeof(*pa));
pa = malloc(sizeof(int));
printf("%d\n",sizeof(*pa));
pa = malloc(sizeof(char));
printf("%d\n",sizeof(*pa));
pa = malloc(0);
printf("%d\n",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?
回答1:
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).
来源:https://stackoverflow.com/questions/32641228/why-using-sizeof-in-malloc