Re: Implementing overloaded operator new[]/delete[]
* James Kanze:
On Sep 24, 1:25 pm, "Alf P. Steinbach" <al...@start.no> wrote:
* James Kanze:
On Sep 23, 11:56 pm, "Alf P. Steinbach" <al...@start.no> wrote:
[...]
No. Actually, apart from implementing your own per-class allocation
scheme, the main use of implementing your own allocator function that
I'm aware of is to obfuscate the new'ing of an instance of the class in
question, so that you're in practice ensured that only your own special
macro for that is used, which then guarantees that the pointer produced
is wrapped in a suitable smart pointer.
That doesn't work.
It works.
Maybe we're talking about different things. I thought I
understood that you defined a macro with the name "new", e.g.:
#define new new( __FILE__, __LINE__ )
That doesn't work; formally, it's undefined behavior, and
practically, it's going to cause no end of havoc as soon as you
include something like <vector> (unless, of course, you're
compiler supports "export", and the library was written with
this in mind).
The macro will look something like
#define NEW( Type, Args ) ungrokkablegoobledygookexpression
You will never type ungrokkablegoobledygookexpression by accident as new
or new[] expression.
And I suspect that most C++ programmers, by definition mediocre, will
not even be able to figure out how to write
ungrokkablegoobledygookexpression, except by inspecting the macro.
For details you can check out my old pointers introduction.
[snip]
How does a debugger tell you what happened in the past? Where a
block was allocated, if it turns out to have leaked, for
example. For that matter, how does it tell you you've
overwritten beyond the end of an allocated block?
The compiler emits debugging meta-information, ordinary allocations are
replaced with operations that keep some meta-information, memory is
initialized to special bit-patterns, and so on, to help the debugger.
In short, the compiler + runtime library does the job that can be done
manually, plus things that can't be done manually, in support of
debugging. An example of debug output information (showing the source
code line that allocated some block that wasn't subsequently
deallocated) is shown at <url:
http://msdn2.microsoft.com/en-us/library/e5ewb1h3(VS.80).aspx>.
However, detecting write-beyond-end-of-block is in general not feasible,
because the granularity of protection offered by an OS is typically 4K
or larger, one page. It can be done (e.g., in Windows, using
pageheap.exe, which I searched up now, never used it!), but at the cost
of allocating one extra protection page for each allocation. That
particular problem is easier dealt with at higher levels, e.g. using
std::vector::at instead of operator[], or simply sound design... ;-)
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?