为什么在malloc中使用sizeof?

CIs*_*ies -3 c malloc sizeof

在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;
}
Run Code Online (Sandbox Code Playgroud)

我有:

8
8
8
8
Run Code Online (Sandbox Code Playgroud)

我猜测因为pa是类型struct A *并且struct A是8字节长,然后malloc分配8个字节,因为它应该,但如果是这样,为什么使用sizeof?

nne*_*neo 6

sizeof不返回已分配的内存块的大小(C没有获取该信息的标准方法); 它根据操作数的类型返回操作数的大小.由于您的指针是类型struct A*,因此sizeof操作数是类型struct A,因此sizeof始终返回8.

因此,即使为10000字节结构分配1个字节,您仍将看到sizeof返回10000.

如果你没有为该对象分配足够的内存(例如因为sizeof(int)<sizeof(struct A))但是你试图使用该对象,你会遇到未定义的行为 - 你的程序不再被很好地定义了可能会发生(没有,崩溃,内存损坏,黑客拥有你的计算机).