Frank Frank - 1 month ago 5
C Question

How to utilize sizeof() to return the size of malloc buffer allocation

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

Answer

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.

Comments