0

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
jramm
  • 6,415
  • 4
  • 34
  • 73
  • 1
    Warning: when calling `sizeof` in `malloc` (and the like) [you should write it](http://stackoverflow.com/a/17258659/1151654) as `ptr = malloc(sizeof(*ptr) * ...);` instead of `ptr = malloc(sizeof(ptrtype*) * ...);`. Here, for instance, you should write `malloc(sizeof(*(bt->node[n].key))*(*keylen));` – Eregrith May 20 '15 at 14:38

3 Answers3

4

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.

3

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().

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

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.

Eregrith
  • 4,263
  • 18
  • 39