Reputation: 6665
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
.
With the debugger running, I can verify that keylen
is 5
.
But if I put:
int kl = sizeof(bt->node[n].key) / sizeof(bt->node[n].key[0])
kl
is 4
.
What did I do wrong?
Upvotes: 0
Views: 854
Reputation: 4366
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
And 8 / 2
equals 4.
Upvotes: 1
Reputation: 134416
sizeof
operator produces the size of a type
, not the amount of memory allocated to a pointer.
In your case, what happenning is
key
is of type int16_t *
sizeof(bt->node[n].key)
gives sizeof(int16_t *)
which on 64 bit, 8
sizeof(bt->node[n].key[0])
which is sizeof(int16_t )
, which is 2
Ultimately, it's 8/2
= 4.
There is absolutely no measurement of the amount of memory returned by malloc()
.
Upvotes: 3
Reputation: 716
Look carefully, you are confusing the pointer with the array:
Where bt->node[n].key is a pointer to 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).
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.
Upvotes: 4