【问题标题】:size of array allocated with malloc is showing one less than expected使用 malloc 分配的数组大小显示比预期小一
【发布时间】:2015-08-01 21:19:03
【问题描述】:
我有这个:
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。
我做错了什么?
【问题讨论】:
-
警告:当在malloc(等)you should write it 中以ptr = malloc(sizeof(*ptr) * ...); 而非ptr = malloc(sizeof(ptrtype*) * ...); 调用sizeof。例如,您应该在这里写malloc(sizeof(*(bt->node[n].key))*(*keylen));
标签:
c
arrays
pointers
malloc
sizeof
【解决方案1】:
仔细看,你把指针和数组搞混了:
其中 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。
【解决方案2】:
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() 返回的内存量绝对没有测量值。
【解决方案3】:
sizeof(bt->node[n].key) 是 sizeof(uint16_t*) 可能是 8(64 位)
sizeof(bt->node[n].key[0]) 是 sizeof(*(uint16_t*)) 是 2
而8 / 2 等于 4。