C malloc allocated only 8 bytes for int * [duplicate]

落爺英雄遲暮 提交于 2020-01-30 05:13:57

问题


I'm trying to create a pointer to a 6 element int in a function to return it later, so for that purpose I'm using malloc, but it seems to be acting not as I expected. Here's the code:

int j = 0;
for (;j < 5; j++) {
    int * intBig = malloc(j * sizeof(int));
    printf("sizeof intBig - %ld\n", sizeof(intBig));
}

Prints the same number 8 bytes as the sizeof(intBig) at each iteration. Whereas I would expect a series of 4, 8, 12, 16. What am I missing in this instance?


回答1:


This is because you're printing the size of an int *. Such a pointer always has the same size. sizeof is a compiler construct. It cannot know things that only occur at runtime, such as dynamic memory allocation. Would it be something like

int intBig[100];

then you would get the size of the array back (in bytes), because the compiler knows how large it is. But the result of the sizeof operator is always a compile-time constant¹, so there is no way what you have there could yield anything else.

Besides, you have a memory leak there because you're not free-ing your memory again.


¹ Variable Length Arrays (VLA) are an exception, but they were not used here.




回答2:


You cannot use sizeof to figure out the size of a memory block returned from malloc().

Except for variable length arrays in C99 and later, sizeof works only on statically known sizes.




回答3:


Because every time you are printing the size of a pointer which is the size of an address which is 8 bytes.




回答4:


sizeof tells you the size of the pointer intBig, not what it points to.

There's no standard way to discover the size of the memory block it points to, so you have to remember that separately.

If you have access to C++, just use std::vector for your dynamic array needs... it knows its size and doesn't forget to deallocate.



来源:https://stackoverflow.com/questions/18854314/c-malloc-allocated-only-8-bytes-for-int

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