Reputation: 2383
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
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
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