[英]why using sizeof in malloc?
When executing this code on IDEONE:在 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?我猜因为
pa
的类型是struct A *
并且struct A
长度是 8 个字节,那么 malloc 应该分配 8 个字节,但如果是这样,为什么要使用 sizeof?
sizeof
doesn't return the size of the memory block that was allocated (C does NOT have a standard way to get that information); sizeof
不返回分配的内存块的大小(C 没有标准方法来获取该信息); 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.由于您的指针的类型为
struct A*
,因此 sizeof 操作数的类型为struct A
,因此 sizeof 始终返回 8。
So, even if you allocate 1 byte for a 10000 byte structure, you will still see sizeof
return 10000.因此,即使您为 10000 字节的结构分配了 1 个字节,您仍然会看到
sizeof
返回 10000。
If you don't allocate enough memory for that object (eg 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).如果您没有为该对象分配足够的内存(例如,因为 sizeof(int) < sizeof(struct A))但您无论如何都尝试使用该对象,您将遇到未定义的行为 - 您的程序不再明确定义和任何东西可能发生(什么也没有、崩溃、内存损坏、黑客拥有您的计算机)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.