简体   繁体   English

用malloc分配的数组的大小显示比预期少一

[英]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 . 运行调试器后,我可以验证keylen5

But if I put: 但是如果我放:

int kl = sizeof(bt->node[n].key) / sizeof(bt->node[n].key[0])

kl is 4 . kl4

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].keysizeof <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.

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