[英]size of array allocated with malloc is showing one less than expected
我有这个:
alloc(Btree *bt, uint8_t *keylen, int16_t n)
{
bt->node[n].key = malloc(sizeof(int16_t)*(*keylen));
{
其中bt->node[n].key
是指向int16_t
的指针。
运行调试器后,我可以验证keylen
为5
。
但是如果我放:
int kl = sizeof(bt->node[n].key) / sizeof(bt->node[n].key[0])
kl
是4
。
我做错了什么?
仔细看,您将指针与数组混淆了:
其中bt-> node [n] .key是指向int16_t的指针。
因此,bt-> node [n] .key是指向已分配内存的指针,而不是分配的内存本身,而sizeof bt->node[n].key
是sizeof <pointer to ...>
,在您的系统中是8(64位)。
8 / sizeof uint16_t = 8 / 2 = 4
您无法检查已分配内存块的大小,必须信任malloc()
才能正常工作,否则请返回NULL
。
sizeof
运算符产生type
的大小 ,而不是分配给指针的内存量。
在你的情况下,发生的是
key
的类型为int16_t *
sizeof(bt->node[n].key)
给出sizeof(int16_t *)
在64位8
sizeof(bt->node[n].key[0])
是sizeof(int16_t )
,是2
最终,它是8/2
= 4。
绝对没有malloc()
返回的malloc()
量的度量。
sizeof(bt->node[n].key)
是sizeof(uint16_t*)
可以是8(64位) sizeof(bt->node[n].key[0])
是sizeof(*(uint16_t*))
是2
和8 / 2
等于4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.