fifamaniac04
fifamaniac04

Reputation: 2383

How to find the number of bytes allocated by malloc

I have the following code:

    int size = 0;
void* ptr; 

ptr = malloc(9); //we want to allocate 9 bytes

size = sizeof(*ptr); 
printf("size = %d\n", size);

This results in size equal to 1. Is there a way for size to be 9??

Upvotes: 3

Views: 3725

Answers (2)

Antzi
Antzi

Reputation: 13444

No. If you want to remember the size of the memory allocated by malloc, you should store it somewhere else.

You could also use an array, then sizeof would gives you an appropriate result... But it wouldn't work anyway if you use a void * type.

Upvotes: 1

Lee Duhem
Lee Duhem

Reputation: 15121

Is there a way for size to be 9??

There is no portable way to find that out.

But if you are using GNU system (Glibc), you could use malloc_usable_size(3).

Note: the size returned by malloc_usable_size could be larger than the size given to corresponding malloc.

Upvotes: 4

Related Questions