473,831 Members | 2,230 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

global operator new

hi,
i want to redefine the global operator new for logging
and stats purposes. is it a good idea to use malloc()
as allocation function ? or should i call one of those
weird crt functions....or ask the OS directly?

oh and another question: which parts of my program will
actually use my version of new ? only the ones that include
the declaration (do i even need one or is a definition in a
cpp file ok?). what about statically linked libs, and what
about the C++ standard libs? what about dlls?
will they all use the new new ? ;)

thanks
martin
Jul 22 '05 #1
7 2160
Martin Stich wrote:
hi,
i want to redefine the global operator new for logging
and stats purposes. is it a good idea to use malloc()
as allocation function ? or should i call one of those
weird crt functions....or ask the OS directly?

oh and another question: which parts of my program will
actually use my version of new ? only the ones that include
the declaration (do i even need one or is a definition in a
cpp file ok?). what about statically linked libs, and what
about the C++ standard libs? what about dlls?
will they all use the new new ? ;)


The right answer to this question is "implementa tion defined".

Each C++ compiler implementation has different answers to your question
(even different versions of the same compiler).

malloc is an excellent place to trap memory allocation calls but for C++
a compiler is able to "inline" new operations and so requests that end
up in malloc may or may not be truly "allocated" as a C++ object.

However, to be friendly to leak detection libs, some C++ implementations
allow you to substitute the regular allocator for a simple malloc
allocator. e.g. in the latest gcc compiler, you can simply set an
environment variable and "viola" you get malloc called for every new and
free for every delete (for classes using the regular gcc allocator).

Jul 22 '05 #2
On Fri, 28 Nov 2003 03:21:13 +0100, "Martin Stich"
<ms****@primusn etz.de> wrote:
hi,
i want to redefine the global operator new for logging
and stats purposes. is it a good idea to use malloc()
as allocation function ?
Yes, it has the right guarantees about alignment, etc., and is easy to
use and standard.

or should i call one of thoseweird crt functions....or ask the OS directly?
Only call something else if you have special performance requirements,
etc.
oh and another question: which parts of my program will
actually use my version of new ? only the ones that include
the declaration (do i even need one or is a definition in a
cpp file ok?).
Since the declaration is exactly the same as the standard global
operator new, including it makes no difference.

what about statically linked libs, and whatabout the C++ standard libs? what about dlls?
will they all use the new new ? ;)


Probably not. Statically linked libs probably will, dlls probably
won't, but this is platform dependent. i.e. the results will probably
be different with .so's under Linux and .dll's under Windows.

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #3

"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:bq******** @dispatch.conce ntric.net...
Martin Stich wrote:
hi,
i want to redefine the global operator new for logging
and stats purposes. is it a good idea to use malloc()
as allocation function ? or should i call one of those
weird crt functions....or ask the OS directly?

oh and another question: which parts of my program will
actually use my version of new ? only the ones that include
the declaration (do i even need one or is a definition in a
cpp file ok?). what about statically linked libs, and what
about the C++ standard libs? what about dlls?
will they all use the new new ? ;)


The right answer to this question is "implementa tion defined".

Each C++ compiler implementation has different answers to your question
(even different versions of the same compiler).

malloc is an excellent place to trap memory allocation calls but for C++
a compiler is able to "inline" new operations and so requests that end
up in malloc may or may not be truly "allocated" as a C++ object.

[SNIP]

Hi Gianni,
could you please elaborate on the "may or may not" part. If I understand you
correctly you indicate that due to the use of malloc inside ones own
implementation of new it is not for sure that the object is constructed. In
my experience the following code worked just fine also for objects, but I
don't wanna claim to be an export on implementations of memory allocators.

void* operator new(size_t Bytes, const char* pFile , int Line )
{
return CMemObserver::G etRef().Allocat e( Bytes, pFile, Line );
};

void* CMemObserver::A llocate( size_t Bytes, const char* pFile, int Line ) {
void* pPtr = malloc( Bytes);
if( !pPtr )
throw std::bad_alloc( ); // ANSI/ISO compliant behavior
m_MemoryMap[pPtr] = CNewData( pFile, Line);
return pPtr;
}

Any further insight or hints for improvements are more than welcome.

Cheers
Chris
Jul 22 '05 #4
Chris Theis wrote:
....

Hi Gianni,
could you please elaborate on the "may or may not" part. If I understand you
correctly you indicate that due to the use of malloc inside ones own
implementation of new it is not for sure that the object is constructed. In
my experience the following code worked just fine also for objects, but I
don't wanna claim to be an export on implementations of memory allocators.

void* operator new(size_t Bytes, const char* pFile , int Line )
{
return CMemObserver::G etRef().Allocat e( Bytes, pFile, Line );
};

void* CMemObserver::A llocate( size_t Bytes, const char* pFile, int Line ) {
void* pPtr = malloc( Bytes);
if( !pPtr )
throw std::bad_alloc( ); // ANSI/ISO compliant behavior
m_MemoryMap[pPtr] = CNewData( pFile, Line);
return pPtr;
}

Any further insight or hints for improvements are more than welcome.


"may or may noy" refers to how some compiler implementations define
opertor new to have a "caching" behaviour. Have a look at the regular
new operator for the latest GCC C++ compiler - if you have libraries
that use this allocator, defining your own allocator will not change the
allocator in the library.

Also, if a class defined it's own new operator, your global new operator
will not be used.

Hence, I think the best way to gets stats on object level memory
allocation is implementation dependant, in GCC for example, the best
mechanism is to substitute malloc/free etc and to set the magic
environment variable GLIBCXX_FORCE_N EW (or GLIBCPP_FORCE_N EW depending
on version).

See:
http://gcc.gnu.org/onlinedocs/libstd...t/howto.html#3

The solution you propose is fine if you only care about the classes in
modules you have control over and you need to be careful that the
allocation of an object uses the corresponding deallocator for
destruction. This is not allways true when you have "standard" objects
being allocated and deallocated in different modules. "namespaces " may
come to the rescue here, I'm not sure but it seems likely that an
"global" new operator defined in a namespace will only apply to classes
in that namespace.

However, if you're looking at leak detection or "stats", usually you're
looking for results from the entire application hence finding a way to
trap all dynamic construction events is the ultimate goal. The nice
thing about trapping malloc/free is that it also traps regular C
libraries as well and hence mixed C/C++ applications are also caught.
Jul 22 '05 #5

gianni,
thanks for your detailed tips!
so if i understand this correctly, in order to trap _all_ allocs of
a program, even the ones from static (and dynamic - is this even
possible?) libs, malloc/realloc/calloc/free instead of the new/delete
operators should be replaced ? or both (if so, do i have to define my
own placement new, too?) ? how would i replace malloc etc...those
are macros, right ? so would i #undef them and then redefine them..
to what ? and how would external libs know i replaced the macros,
since they dont include my code ?
since i use vc++ and not gcc, unfortunately the url doesnt help me
a lot. how can i assure i am really trapping all allocs, and didnt miss
one...is there a way of testing this ?
sorry these are so many new questions - didnt know the subject was
that complex ;)

thanks
martin

Jul 22 '05 #6
Martin Stich wrote:
gianni,
thanks for your detailed tips!
so if i understand this correctly, in order to trap _all_ allocs of
a program, even the ones from static (and dynamic - is this even
possible?) libs, malloc/realloc/calloc/free instead of the new/delete
operators should be replaced ? or both (if so, do i have to define my
own placement new, too?) ? how would i replace malloc etc...those
are macros, right ? so would i #undef them and then redefine them..
to what ? and how would external libs know i replaced the macros,
since they dont include my code ?
since i use vc++ and not gcc, unfortunately the url doesnt help me
a lot. how can i assure i am really trapping all allocs, and didnt miss
one...is there a way of testing this ?
sorry these are so many new questions - didnt know the subject was
that complex ;)


I've not had that much success doing what you ask with visual studio (I
have not really tried that hard).

The point I was trying to make is that this is platform specific and
really off-topic for this news-group. You could try one of the
microsoft visual studio news groups, I'm sure you'll get a much better
response that I can give you.

Jul 22 '05 #7

"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:bq******** @dispatch.conce ntric.net...
Chris Theis wrote:
... [SNIP] However, if you're looking at leak detection or "stats", usually you're
looking for results from the entire application hence finding a way to
trap all dynamic construction events is the ultimate goal. The nice
thing about trapping malloc/free is that it also traps regular C
libraries as well and hence mixed C/C++ applications are also caught.


Cheers for the information!

Chris
Jul 22 '05 #8

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

Similar topics

1
3852
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. In fact there are quite a few things that I learned that I did not know before. For example, while I knew that the new and delete operators can be overloaded for classes, I did not know that that the global new and delete operators can also be overloaded. ...
7
2443
by: Emanuel Ziegler | last post by:
Hello, I want to do some mathematics with functions. In my case the function classes are very complex, but this simple example has the same problems. To allow calculations that begin with a double, I have to define a global operator+ (or -*/) and special function classes. --- source begins here ---
44
2051
by: Mohanasundaram | last post by:
int i = 10; int main() { int i = 20; return 0; } Hi All, I want to access the global variable i inside the main. Is there
9
2498
by: Javaman59 | last post by:
I saw in a recent post the :: operator used to reach the global namespace, as in global::MyNamespace I hadn't seen this before, so looked it up in MSDN, which explained it nicely. My question is, do "global" and "::" always go together? Is there any other use for these operators, than as a pair? TIA,
16
3239
by: Roman Ziak | last post by:
Hello, there were times when I used to be looking for a way to access JavaScript Global object similar to those found in VBScript or PHP ($GLOBALS). At present this has only academic value for me. I was doing research on JavaScript inheritance recently (simplifying it in particular) and after reading 10.1.1, 10.1.3 and some other sections of ECMA262 I got a hint on accessing global object from different than global scope.
2
3198
by: ryan_melville | last post by:
Hi, Should I put the operator<<() for my class (which is in a namespace) in the namespace or make it global? If I understand the lookup rules correctly: If I make it global, it may be hidden if called from within a different namespace and that other namespace has any operator<<() defined. That doesn't seem good.
7
2806
by: Eric Lilja | last post by:
>From a book, I know the following is true for the comparison operators: An overloaded operator that is a class member is only considered when the operator is used with a *left* operand that is an object of that class. And is that also the reason why if you use class member functions for operators << and >you have to write: someclass << cout; someclass >cin; ?
3
2625
by: mrstephengross | last post by:
Hi folks. I've got a weird situation--gcc doesn't like the folllowing code snippet, but I don't know if it's correct or not. Here's the situation: In the global namespace, I've got a operator<< declared that will send a vector<Tto a std::ostream. In the "outer" namespace, I've got a operator<< declared that will send a Thing<Tto a std::ostream. In the "outer" namespace, I've got a function "foo" that tries to send a vector<Tto a...
1
29403
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this condition. The opinions expressed in this article are those of the author alone although many have...
1
3634
by: google | last post by:
We need to be able to disable global operator new at compile time. We are developing a large library and need to control all memory allocation and cannot have a mistake whereby a mistaken use of global operator new creeps in. It is not feasible to solve this via implementing our own global operator new which asserts(false), as there is no practical way to test all paths of execution. This is a large and complex library, to say the least....
0
9794
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10778
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10538
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10210
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9319
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7750
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4419
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3967
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.