calculating the size of a pointers data

hi
If c[N] represents array we can find out the size of array like this
sizeof c / sizeof *c.

Is there a similar way to find the size of memory allocated using new operator, through the pointer which points to the memory.

(i.e)
int *i;
i = new int[10];


is there a way to find the size of memory pointed by i as 10;

we can delete the memory pointed by i as delete []i; so i think the compiler may be knowing the size of memory pointed by i.
Last edited on
Short answer is no you can't get the allocation size using an API or OS call. The only way to do it is to track the size of the allocation yourself.
This FAQ discusses it a bit.

http://c-faq.com/malloc/querysize.html
thank u
But how does the delete keyword know about the size of memory pointed by a pointer.
The operating system holds a record of all the allocations and their starting addresses. So when you call delete it looks up the pointer you pass in, in its records and then knows what memory needs to be released.
Actually it's the C++ memory manager that knows how many elements are in the array because the destructor needs to be called for each element. OS knows nothing about destructors.
You're right the OS knows nothing about destructors but the destructor calls delete which is an OS call. In fact delete usually calls free like new calls malloc.
Topic archived. No new replies allowed.