Re: how to get size of memory allocated
On 10 Nov., 10:28, James Kanze <james.ka...@gmail.com> wrote:
On Nov 10, 8:14 am, peter koch <peter.koch.lar...@gmail.com> wrote:
On 10 Nov., 06:37, mithun <mithunsi...@gmail.com> wrote:
In the following code snippet ....
#include<stdio.h>
#include<iostream>
using namespace std;
class A
{
int a,b;
char c,d;
};
main()
{
A *a = new A();
cout<<"\n"<<sizeof(a);
}
The following code gives output 4 as 'a' is pointer. I want
to get the complete size of object allocated ie 10. How can
this be done.
I would guess sizeof A to be 12, not 10.
It depends on the machine. I'm aware of processors where it
will be 18, and I've heard of some where it will be 4. (But on
common desktop machines, yes, it will be 12.)
Yes. My guess was based on the information from the post, strongly
indicating a size of 12.
It is trivial to get the size of an A, but that does not give
the size of the memory allocated. At least sizeof A bytes will
be allocated, but it could easily be more - 12, 16, 24 and 32
would be probable numbers.
Off hand, I don't know of any system where the amount of memory
allocated will not be at least a pointer more than what is
requested. Typically, alignment considerations, the algorithm
and such may make it even more. Sometimes much more. (IIRC,
the malloc bundled with the Berkley kernel would add 8, then
round up to the next power of 2.)
Some allocators are optimised to provide no overhead for small
allocations - and I guess a size of 12 would be small. In such a case,
it would be possible to have a zero size overhead. I don't know if any
implementation of new uses such a strategy by default, but if not, you
could write your own (or grab the one implemented by Alexandrescu).
/Peter