why using sizeof in malloc?

大兔子大兔子 提交于 2019-12-13 09:54:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!