473,395 Members | 1,341 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

memory size allocated by new

This question has been posted to this forum before and I read the
thread but found that the answers were perhaps imcomplete, so I am
trying again.

Whenever I am creating objects I would like to keep track of the
memory which is used for each object (for stats purpose). They are 2
basic approaches, one is to write a Memory manager type of class where
new & delete would be overloading the standard new & delete operator.
Each time the new member function of this class would be called I
could update a variable to would keep track of the bytes allocated by
new. This not completly satisafactory for me as this would be global
to the application.

Another way is to just recompute the size of the byte arrays and add
the result to a member variable. Something like that...

class A
{
private:
int *data;
float *floatData;
size_t mem;
public:
A( size_t arraySize, size_t arraySize2 )
{
mem = 0;
data = new int[ arraySize ];
dataFloat = new float[ arraySize2 ]
mem += sizeof( int ) * arraySize;
mem += sizeof( float ) * arraySize2;
}
}

I have read that 'new' reserves the memory which is needed for the
array of a certain type, plus some additional info at the beginning at
this array (which delete uses to know what is the size of the array it
needs to free). So instead of recompute the size of the array in bytes
and summing up the result to the variable mem is there a way one could
access the size of an array in bytes used by an array or created by
new ?

thanks -

Mar 7 '07 #1
11 2608
On Mar 6, 7:59 pm, "mast...@yahoo.com" <mast...@yahoo.comwrote:
This question has been posted to this forum before and I read the
thread but found that the answers were perhaps imcomplete, so I am
trying again.

Whenever I am creating objects I would like to keep track of the
memory which is used for each object (for stats purpose). They are 2
basic approaches, one is to write a Memory manager type of class where
new & delete would be overloading the standard new & delete operator.
Each time the new member function of this class would be called I
could update a variable to would keep track of the bytes allocated by
new. This not completly satisafactory for me as this would be global
to the application.
Sorry, I'm not understanding you. Are you asking for some way of
tracking how many bytes are being allocated globally? Or only in
certain spots?
Another way is to just recompute the size of the byte arrays and add
the result to a member variable. Something like that...

class A
{
private:
int *data;
float *floatData;
size_t mem;
public:
A( size_t arraySize, size_t arraySize2 )
{
mem = 0;
data = new int[ arraySize ];
dataFloat = new float[ arraySize2 ]
mem += sizeof( int ) * arraySize;
mem += sizeof( float ) * arraySize2;
}

}
I'm not getting this either. You are allocating arrays, and trying to
store the size of the arrays, but you only want it done in a class?
I have read that 'new' reserves the memory which is needed for the
array of a certain type, plus some additional info at the beginning at
this array (which delete uses to know what is the size of the array it
needs to free). So instead of recompute the size of the array in bytes
and summing up the result to the variable mem is there a way one could
access the size of an array in bytes used by an array or created by
new ?
Ok, this I get. An array will be sizeof(type)*numberOfElements but if
the type has a destructor, then you will have to add sizeof(size_t) to
it.

If you just want to know how many bytes are being allocated globally,
do this:

<sourceFile>
static size_t bytesAllocatedSoFar = 0;

void* ::operator new(size_t size)
{
bytesAllocatedSoFar += size;
return malloc(size);
}

void* ::operator new[](size_t size)
{
bytesAllocatedSoFar += size;
return malloc(size);
}

void ::operator delete(void *memory)
{
return free(memory);
}

void ::operator delete[](void *memory)
{
return free(memory);
}
</sourceFile>

But if any part of your programme uses malloc, this information is
lost.

If you want to access bytesAllocatedSoFar you will either define it
extern in the header file (and remove static from the source file), or
create an access function prototype in the header file and define it
in the source as returning bytesAllocatedSoFar.

Hope this helps.
Adrian

Mar 7 '07 #2
ma*****@yahoo.com wrote:
This question has been posted to this forum before and I read the
thread but found that the answers were perhaps imcomplete, so I am
trying again.

Whenever I am creating objects I would like to keep track of the
memory which is used for each object (for stats purpose). They are 2
basic approaches, one is to write a Memory manager type of class where
new & delete would be overloading the standard new & delete operator.
Each time the new member function of this class would be called I
could update a variable to would keep track of the bytes allocated by
new. This not completly satisafactory for me as this would be global
to the application.

Another way is to just recompute the size of the byte arrays and add
the result to a member variable. Something like that...

class A
{
private:
int *data;
float *floatData;
size_t mem;
public:
A( size_t arraySize, size_t arraySize2 )
{
mem = 0;
data = new int[ arraySize ];
dataFloat = new float[ arraySize2 ]
mem += sizeof( int ) * arraySize;
mem += sizeof( float ) * arraySize2;
}
}

I have read that 'new' reserves the memory which is needed for the
array of a certain type, plus some additional info at the beginning at
this array (which delete uses to know what is the size of the array it
needs to free). So instead of recompute the size of the array in bytes
and summing up the result to the variable mem is there a way one could
access the size of an array in bytes used by an array or created by
new ?

thanks -

Your class is defective and sloppy. I'd write it like this:

class A {
private:
std::vector<intdata;
std::vector<floatfloatData;
public:
A(size_t arraySize, size_t arraySize2) :
data(arraySize), floatData(arraySize2) { }
size_t approximate_size() {
return data.size() * sizeof(int) +
floatData.size() * sizeof(float);
}
};

By using vector, you class automatically becomes well defined in copy
and assignment. Further it frees you from having to worry about
memory allocation. You can easily change the size as well.

The approximate_size function returns the smae thing your "mem"
variable would have, but only needs be calculated when used (and
is correct in light of resizing of the vectors).
Mar 7 '07 #3
>
Sorry, I'm not understanding you. Are you asking for some way of
tracking how many bytes are being allocated globally? Or only in
certain spots?
Sorry Adrian I wasn't clear. I am only interested in the memory used
by objects of class A. So for example if they are 100 objects of class
A which are created all with different sizes for floatData & data, I
want to know how memory is used by these 100 objects. This is why I
wanted to avoid using some sort of memory manager class that would
have new and delete overloaded.

My question was also about these extra bits that the new operator
seems to control to save info about the size of the byte arrays it has
created. I was wondering if that info could be accessed somehow, so
one could get that value from there !

Mar 7 '07 #4
ad*************@gmail.com wrote:
>
Ok, this I get. An array will be sizeof(type)*numberOfElements but if
the type has a destructor, then you will have to add sizeof(size_t) to
it.
That's something reserved to the implementation. All the standard says
is the size passed to the operator new for arrays is some fixed
(possibly zero) size PLUS the number of elements * sizeof the element.
>
Mar 7 '07 #5
On Mar 6, 9:30 pm, Ron Natalie <r...@spamcop.netwrote:
adrian.hawry...@gmail.com wrote:
Ok, this I get. An array will be sizeof(type)*numberOfElements but if
the type has a destructor, then you will have to add sizeof(size_t) to
it.

That's something reserved to the implementation. All the standard says
is the size passed to the operator new for arrays is some fixed
(possibly zero) size PLUS the number of elements * sizeof the element.

True. What I state is the minimum. There could be other data that I
have not accounted for.
Adrian

Mar 7 '07 #6
On Mar 6, 9:25 pm, "mast...@yahoo.com" <mast...@yahoo.comwrote:
Sorry, I'm not understanding you. Are you asking for some way of
tracking how many bytes are being allocated globally? Or only in
certain spots?

Sorry Adrian I wasn't clear. I am only interested in the memory used
by objects of class A. So for example if they are 100 objects of class
A which are created all with different sizes for floatData & data, I
want to know how memory is used by these 100 objects. This is why I
wanted to avoid using some sort of memory manager class that would
have new and delete overloaded.

My question was also about these extra bits that the new operator
seems to control to save info about the size of the byte arrays it has
created. I was wondering if that info could be accessed somehow, so
one could get that value from there !
First off, the new operator does not 'control' the number of bytes it
allocates, unless by control, you mean add to beyond what the compiler
is going to add to it. I.e. I stated that there could be a size_t
value at the begining of an array, this is done by the compiler, not
the new operator. The new operator is passed the size the compiler
needs to do its thing, and as stated by Ron, it is implementation
dependent. However, the new operator can add extra stuff if it wants,
as long as the returned pointer points to the space that the compiler
can use.

The following is untested, (I just wrote it) but it should work. It
basicly wraps the new operator in a class template. Destructors
should be called approprately.

<headerFile>
/************************************************** **********
* Written by Adrian Hawryluk (C) Mar 6, 2007
* ----------------------------------------------------------
* You may use and add to this free of charge, but
* please keep this header intact, and if you modify
* please share your mods with everyone else.
*
* Usage:
*
* int * integer = alloc<int>::newObj();
* cout << allocBase::totalBytesAllocated() << endl; // 4
* int * intArray = alloc<int>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 80
*
* class foo {
* int bar;
* public: ~foo() {}
* };
*
* foo * fooArray = alloc<foo>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 84?
*
************************************************** **********/
class allocBase
{
static size_t bytesAllocatedSoFar;
public:
static size_t totalBytesAllocated() { return bytesAllocatedSoFar; }
};

template<class T>
class alloc{
T obj;
void * operator new(size_t size) { bytesAllocatedSoFar += size;
return ::operator new(size); }
void * operator new[](size_t size) { bytesAllocatedSoFar += size;
return ::operator new(size); }

public:
static T* newObj() { return reinterpret_cast<T*>(new T()); }
static T* newObjArray(int numberOfElements) { return
reinterpret_cast<T*>(new T[numberOfElements]); }
};
</headerFile>

<sourceFile>
size_t allocBase::bytesAllocatedSoFar = 0;
</sourceFile>

Enjoy,
Adrian

Mar 7 '07 #7
On Mar 6, 11:04 pm, adrian.hawry...@gmail.com wrote:
On Mar 6, 9:25 pm, "mast...@yahoo.com" <mast...@yahoo.comwrote:
Sorry, I'm not understanding you. Are you asking for some way of
tracking how many bytes are being allocated globally? Or only in
certain spots?
Sorry Adrian I wasn't clear. I am only interested in the memory used
by objects of class A. So for example if they are 100 objects of class
A which are created all with different sizes for floatData & data, I
want to know how memory is used by these 100 objects. This is why I
wanted to avoid using some sort of memory manager class that would
have new and delete overloaded.
My question was also about these extra bits that the new operator
seems to control to save info about the size of the byte arrays it has
created. I was wondering if that info could be accessed somehow, so
one could get that value from there !

First off, the new operator does not 'control' the number of bytes it
allocates, unless by control, you mean add to beyond what the compiler
is going to add to it. I.e. I stated that there could be a size_t
value at the begining of an array, this is done by the compiler, not
the new operator. The new operator is passed the size the compiler
needs to do its thing, and as stated by Ron, it is implementation
dependent. However, the new operator can add extra stuff if it wants,
as long as the returned pointer points to the space that the compiler
can use.

The following is untested, (I just wrote it) but it should work. It
basicly wraps the new operator in a class template. Destructors
should be called approprately.

<headerFile>
/************************************************** **********
* Written by Adrian Hawryluk (C) Mar 6, 2007
* ----------------------------------------------------------
* You may use and add to this free of charge, but
* please keep this header intact, and if you modify
* please share your mods with everyone else.
*
* Usage:
*
* int * integer = alloc<int>::newObj();
* cout << allocBase::totalBytesAllocated() << endl; // 4
* int * intArray = alloc<int>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 80
*
* class foo {
* int bar;
* public: ~foo() {}
* };
*
* foo * fooArray = alloc<foo>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 84?
*
************************************************** **********/
class allocBase
{
static size_t bytesAllocatedSoFar;
public:
static size_t totalBytesAllocated() { return bytesAllocatedSoFar; }

};

template<class T>
class alloc{
T obj;
void * operator new(size_t size) { bytesAllocatedSoFar += size;
return ::operator new(size); }
void * operator new[](size_t size) { bytesAllocatedSoFar += size;
return ::operator new(size); }
Er, I think that I should be newing alloc<T>'s not T's.

public:
static T* newObj() { return reinterpret_cast<T*>(new alloc<T>()); }
static T* newObjArray(int numberOfElements) { return
reinterpret_cast<T*>(new alloc<T>[numberOfElements]); }
public:
static T* newObj() { return reinterpret_cast<T*>(new T()); }
static T* newObjArray(int numberOfElements) { return
reinterpret_cast<T*>(new T[numberOfElements]); }};

</headerFile>

<sourceFile>
size_t allocBase::bytesAllocatedSoFar = 0;
</sourceFile>

Enjoy,

Adrian


Mar 7 '07 #8
>
First off, the new operator does not 'control' the number of bytes it
allocates, unless by control, you mean add to beyond what the compiler
is going to add to it. I.e. I stated that there could be a size_t
....

Thanks Adrian,
Yes I had read that this was managed by the compiler indeed. I guess
that ansers my question well. Unless i add extra stuff as you say to
new operator, there's no more 'direct' way to get that information.
Thanks a lot for your help.

Mar 7 '07 #9
On Mar 6, 11:04 pm, adrian.hawry...@gmail.com wrote:
<headerFile>
/************************************************** **********
* Written by Adrian Hawryluk (C) Mar 6, 2007
* ----------------------------------------------------------
* You may use and add to this free of charge, but
* please keep this header intact, and if you modify
* please share your mods with everyone else.
*
* Usage:
*
* int * integer = alloc<int>::newObj();
* cout << allocBase::totalBytesAllocated() << endl; // 4
* int * intArray = alloc<int>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 80
*
* class foo {
* int bar;
* public: ~foo() {}
* };
*
* foo * fooArray = alloc<foo>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 84?
*
************************************************** **********/
This should read:

/************************************************** **********
* Written by Adrian Hawryluk (C) Mar 6, 2007
* ----------------------------------------------------------
* You may use and add to this free of charge, but
* please keep this header intact, and if you modify
* please share your mods with everyone else.
*
* Usage:
*
* int * integer = alloc<int>::newObj();
* cout << allocBase::totalBytesAllocated() << endl; // 4
* int * intArray = alloc<int>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 84 (80 + 4)
*
* class foo {
* int bar;
* public: ~foo() {}
* };
*
* foo * fooArray = alloc<foo>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 168? (84? +
84)?
*
************************************************** **********/
Adrian

Mar 7 '07 #10
On Mar 7, 1:14 am, "mast...@yahoo.com" <mast...@yahoo.comwrote:
First off, the new operator does not 'control' the number of bytes it
allocates, unless by control, you mean add to beyond what the compiler
is going to add to it. I.e. I stated that there could be a size_t

...

Thanks Adrian,
Yes I had read that this was managed by the compiler indeed. I guess
that ansers my question well. Unless i add extra stuff as you say to
new operator, there's no more 'direct' way to get that information.
Thanks a lot for your help.
So your question is answered? Glad to have helped.
Adrian

Mar 7 '07 #11
In case anybody is interested, here is a complete and tested version
of what I was describing above.

<headerFile>
/************************************************** ************
* Written by Adrian Hawryluk (C) Mar 6, 2007
* -------------------------------------------------------------
* You may use and add to this free of charge, but
* please keep this header intact, and if you modify
* please share your mods with everyone else.
*
* Usage:
*
* int * integer = alloc<int>::newObj(3);
* cout << allocBase::totalBytesAllocated() // 4
* << endl
* << "*integer = " << *integer << endl;
* delete integer;
*
* int * intArray = alloc<int>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() // 84 (80 + 4)
* << endl
* << "*intArray = " << *intArray << endl;
* delete[] intArray;
*
* // Class located outside of the function where this code
* // is running.
* class foo {
* int bar;
* public:
* ~foo() {}
* };
*
* foo * fooArray = alloc<foo>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() // 168? (84? + 84)
* << endl;
* // ? indicates that the returned value is compiler dependent
* delete[] fooArray;
*
************************************************** ************/
class allocBase
{
protected:
static size_t bytesAllocatedSoFar;
public:
static size_t totalBytesAllocated() { return bytesAllocatedSoFar; }

};

template<class T>
class alloc : public allocBase {
T obj;

void * operator new(size_t size)
{
bytesAllocatedSoFar += size;
return ::operator new(size);
}

void * operator new[](size_t size) {
bytesAllocatedSoFar += size;
return ::operator new(size);
}

public:
static T* newObj()
{
return reinterpret_cast<T*>(new alloc<T>());
}

static T* newObjArray(int numberOfElements)
{
return reinterpret_cast<T*>(new alloc<T>[numberOfElements]());
}

// creates a new object and assigns it the value objToCopy
// requires that T::operator=(T const&) or copy constructor is
defined
static T* newObj(T const & objToCopy)
{
T* tmp = reinterpret_cast<T*>(new alloc<T>());
*tmp = objToCopy;
return tmp;
}
};
</headerFile>

<sourceFile>
size_t allocBase::bytesAllocatedSoFar = 0;
</sourceFile>

Enjoy.
Adrian

Mar 7 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: hall | last post by:
I have a question regarding where memory is allocated when arrays are created. I'll illustrate this by example. I may be wrong on some details, do feel free to correct me. The code piece: int...
8
by: Tron Thomas | last post by:
As part of applying for a programming position at a company, I recently I had submitted some code samples to one of the developers for review. This is the feedback I received: One of his...
22
by: xixi | last post by:
hi, we are using db2 udb v8.1 for windows, i have changed the buffer pool size to accommadate better performance, say size 200000, if i have multiple connection to the same database from...
5
by: RoSsIaCrIiLoIA | last post by:
why not to build a malloc_m() and a free_m() that *check* (if memory_debug=1) if 1) there are some errors in bounds of *all* allocated arrays from them (and trace-print the path of code that make...
4
by: Hermann Maier | last post by:
hi, i need to find out the memory usage of a specific function that i use in my program. this function does some recursive calculations and i want my program to display the amount of memory the...
74
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique...
26
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I...
94
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring...
6
by: CANCER.0707 | last post by:
The problem statement is as follows Create a library that creates pools of memory of different sizes.For e.g. one pool of 32 byte size, another pool of 64 byte size and so on.Create an array of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.