为什么在malloc中使用sizeof

为什么在malloc中使用sizeof

本文介绍了为什么在malloc中使用sizeof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在IDEONE上执行此代码时:

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;
}

我得到了:

8
8
8
8

我猜因为pa的类型为struct A *并且struct A的长​​度为8个字节,所以malloc应该分配8个字节,但是如果是这样,为什么要使用sizeof?

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?

推荐答案

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

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.

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

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

如果您没有为该对象分配足够的内存(例如,因为sizeof(int)< sizeof(struct A)),但是无论如何尝试使用该对象,您将遇到未定义的行为-程序不再定义明确,可能会发生任何事情(无崩溃,崩溃,内存损坏,黑客拥有您的计算机).

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).

这篇关于为什么在malloc中使用sizeof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:06