[英]size of array allocated with malloc is showing one less than expected
I have this: 我有这个:
alloc(Btree *bt, uint8_t *keylen, int16_t n)
{
bt->node[n].key = malloc(sizeof(int16_t)*(*keylen));
{
Where bt->node[n].key
is a pointer to int16_t
. 其中
bt->node[n].key
是指向int16_t
的指针。
With the debugger running, I can verify that keylen
is 5
. 运行调试器后,我可以验证
keylen
为5
。
But if I put: 但是如果我放:
int kl = sizeof(bt->node[n].key) / sizeof(bt->node[n].key[0])
kl
is 4
. kl
是4
。
What did I do wrong? 我做错了什么?
Look carefully, you are confusing the pointer with the array: 仔细看,您将指针与数组混淆了:
Where bt->node[n].key is a pointer to int16_t.
其中bt-> node [n] .key是指向int16_t的指针。
Thus, bt->node[n].key is a pointer to the allocated memory, not the allocated memory itself, and sizeof bt->node[n].key
is sizeof <pointer to ...>
which, in your system is 8 (64 bits). 因此,bt-> node [n] .key是指向已分配内存的指针,而不是分配的内存本身,而
sizeof bt->node[n].key
是sizeof <pointer to ...>
,在您的系统中是8(64位)。
8 / sizeof uint16_t = 8 / 2 = 4
You can not check the size of the allocated memory chunk, you have to trust malloc()
to work well or return NULL
if it can't. 您无法检查已分配内存块的大小,必须信任
malloc()
才能正常工作,否则请返回NULL
。
sizeof
operator produces the size of a type
, not the amount of memory allocated to a pointer . sizeof
运算符产生type
的大小 ,而不是分配给指针的内存量。
In your case, what happenning is 在你的情况下,发生的是
key
is of type int16_t *
key
的类型为int16_t *
sizeof(bt->node[n].key)
gives sizeof(int16_t *)
which on 64 bit, 8
sizeof(bt->node[n].key)
给出sizeof(int16_t *)
在64位8
sizeof(bt->node[n].key[0])
which is sizeof(int16_t )
, which is 2
sizeof(bt->node[n].key[0])
是sizeof(int16_t )
,是2
Ultimately, it's 8/2
= 4. 最终,它是
8/2
= 4。
There is absolutely no measurement of the amount of memory returned by malloc()
. 绝对没有
malloc()
返回的malloc()
量的度量。
sizeof(bt->node[n].key)
is sizeof(uint16_t*)
which could be 8 (on 64 bits) sizeof(bt->node[n].key[0])
is sizeof(*(uint16_t*))
which is 2 sizeof(bt->node[n].key)
是sizeof(uint16_t*)
可以是8(64位) sizeof(bt->node[n].key[0])
是sizeof(*(uint16_t*))
是2
And 8 / 2
equals 4. 和
8 / 2
等于4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.