calculating the size of a pointers data

Jul 14, 2008 at 9:38am
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 Jul 14, 2008 at 9:39am
Jul 14, 2008 at 10:25am
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
Jul 14, 2008 at 11:58am
thank u
But how does the delete keyword know about the size of memory pointed by a pointer.
Jul 14, 2008 at 12:29pm
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.
Jul 14, 2008 at 1:52pm
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.
Jul 14, 2008 at 6:52pm
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.