简体   繁体   中英

why using sizeof in malloc?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM