-1

If I allocate:

int *d =  malloc(5* sizeof(int));
printf("%d", (int) sizeof(d));

I get a value of 8 instead 5. I know sizeof() is not meant to return the length in this case but I wonder if there is a workaround for that since I want to avoid tracking the size manually ( by parameter passing).

Frank
  • 25
  • 6

5 Answers5

5

sizeof(d) gives the size of the pointer, d. A value of 8 is consistent with a 64-bit host system.

This is distinct from the allocated size of whatever d points at.

Since malloc() allocates at run time (the length to be allocated is specified when the program is run) and sizeof is a compile-time operator, it is not possible to use sizeof to obtain the length.

You need to track the size manually, in a separate variable.

  size_t allocated_size = 5*sizeof int;
  int *d = malloc(allocated_size);
  printf("%d", (int) allocated_size);

It is more common to track the number of elements (i.e. take account of the type of d).

  size_t allocated_ints = 5;
  int *d = malloc(allocated_ints * sizeof (*d));
  printf("%d", (int) allocated_ints);   // prints number of `int`

size_t is defined in <stdlib.h> (among others). In C99 and later, the format specifier for printing a size_t is %zu (rather than converting to int and using %d as you have done).

Peter
  • 35,646
  • 4
  • 32
  • 74
3

When the sizeof operator is applied to a pointer, it gives the size of the pointer itself. It does not give the size of the array it may be pointing to.

When dynamically allocating an array, you need to manually keep track of how many elements you've allocated.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

sizeof cannot provide the information you want. You have to keep track of it yourself.

Jens
  • 69,818
  • 15
  • 125
  • 179
0

C does not track the size of an allocated buffer for you. You must track the size manually.

aschepler
  • 70,891
  • 9
  • 107
  • 161
0

You should first decide how much memory you're going to allocate, then keep track of it in a constant or a variable.

const size_t sz = 5 * sizeof(int);
Ryan
  • 14,392
  • 8
  • 62
  • 102