I am working on the memory allocator/snapshotting component of a runtime data flow/model analyzer module. A part of our requirements is have the data structures of the test program allocated in a custom memory region that is under our control. In order to avoid, changing the test program we figured we have to define our own malloc/frees and the actual snapshotting/runtime checker module would use the system malloc whose pointer we would have got through the LD_PRELOADED mechanism( thanks Stackoverflow ). However, the real problem is with operator new. We could go the same route as before but new might internally use malloc( yet to look at kernel/libstdc++ code to verify this though ) and so we might end up actually using our malloc for both the test program as well as for the runtime checker module.
One solution I could come up with was overloading operator new somehow finding the caller context. ( I usually have a semantic like create a C++ object < set a recursive flag in constructor> clear it in the destructor ), allocate memory using either our malloc our glibc malloc based on the context, then use placement syntax of new to ensure the constructor gets called.
I would really like some pointers on when is the C++ constructor actually invoked, i am 90% sure it is part of new because returns a pointer to that object, but the only implementation of new which i have seen( VSCRT ) uses malloc and does not have an apparent constructor invocation.
My question is:
1) I would like some feedback on my general idea?
2) When is the constructor exactly invoked?
Best,
Subramanian
Whan you overload the
newoperator, you only overload the memory allocation process, not the call to the constructor (that, I believe, is done by the compiler by emitting the necessary code to call the constructor on the space returned bynew) — similar with `delete: only free the allocated space (after the destructor has been called already).So, the quick answer to your question is that you can overload operator
new/deleteto use your specific memory allocation scheme (e.g. viamalloc/free) and the object creation will be taken care of by the generated exectable code.Note: you do not need any extra parameter for the constructor (you can’t even provide one for the destructor) — by the time the constructor is called the memory is successfully allocated (otherwise the constructor would not have been called to begin with)