Ugh, my sympathy. This is going to depend a lot on your compiler, your libc, etc. Some rubber-meets-road strategies that have “worked” to varying degrees for us in the past (/me braces for downvotes) are:
- The
operator new
/operator delete
overloads you suggested — although note that some compilers are picky about not havingthrow()
specs, some really want them, some want them for new but not for delete, etc (I have a giant platform-specific#if
/#elif
block for all of the 4+ platforms we’re working on now). - Also worth noting: you can generally ignore the placement versions, they don’t allocate.
- Look at
__malloc_hook
and friends — note that these are deprecated and have thread race conditions — but they’re nice in that new/delete tend to be implemented in terms ofmalloc
(but not always). - Providing a replacement
malloc
,calloc
,realloc
, andfree
and getting your linker args in the right order so that the overrides take place (this is what gcc recommends these days, although I’ve had situations where it was impossible to do, and I had to use deprecated__malloc_hook
) — again,new
anddelete
tend to be implemented in terms of these, but not always. - Avoiding all the standard allocation methods (
operator new
,malloc
, etc) in “our code” and using custom functions instead — not very easy with existing codebase. - Tracking down the library author and delivering a
savage beatingpolite request or patch to change their library to allow you to specify a different allocator (it may be faster than doing this yourself) — I think this has lead to a cardinal rule of “client always specifies the allocator or does the allocation” with any libraries I write.
Please note that this is not an answer in terms of what the standards say should happen, just my experience. I’ve worked with more than a few buggy/broken compilers and libc implementations in the past, so YMMV. I also have the luxury of working on fairly “sealed systems”, and not being all that worried about portability for any specific application.
Regarding dynamic libraries: I’m currently in a bit of a pinch in this regard myself; our “app” gets loaded as a dynamic .so
and we have to be pretty careful to pass any delete
/free
requests back to the default allocator if they didn’t come from us. The current solution is to just cordon off our allocations to a specific area: if we get a delete/free from within that address range, we dispatch to our handler, otherwise back to the default… I’ve even toyed with (horrors) the idea of checking the caller address to see if it’s in our address space. (The probability of going boom increases with such hacks, though.)
This may be a useful strategy even if you are the process lead and you’re using an outside library: tag or restrict or otherwise identify your own allocs somehow (even going so far as to keep a list of allocs you know about), and then pass on any unknowns. All of this has ugly side-effects and limitations, though.
(Looking forward to other answers!)