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

5
  • 3
    d is a pointer and you are getting its size. That's Why. Commented Oct 19, 2016 at 19:38
  • stackoverflow.com/questions/10639666/… Commented Oct 19, 2016 at 19:40
  • "How to utilize sizeof()...". There's no such "how". There no way to use sizeof for that purpose. Commented Oct 19, 2016 at 19:41
  • 1
    sizeof is not a Function its an Operator. Commented Oct 19, 2016 at 19:42
  • 2
    You know the size. You just told it what to allocate. But you failed to check the returned pointer is not NULL. If it is, 0 bytes were allocated. Else, it allocated the 5* sizeof(int) bytes you requested. Commented Oct 19, 2016 at 19:49

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice Answer :).
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.

1 Comment

When a pointer is passed to sizeof Sounds like sizeof is a function :D
1

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

Comments

0

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

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.