Re: OT: Language War (Re: "C" Manual)
Lo, on Friday, January 4, David Teague did write:
> On Thu, 3 Jan 2002, Richard Cobbe wrote:
> > Not in the general case, no.
> > std::string *s = new string("foo");
> > std::string *s2 = s;
> > delete s;
> > If we assume a variant of C++ that extends delete to set its
> > argument pointer to NULL, you still have the problem of s2 hanging
> > around. In the general case, it's not so obvious that you've got
> > two pointers to reset.
> The allocated memory is released to the free store manager. There is
> no leak.
The original goal was avoiding bogus pointers rather than avoiding
memory leaks. The suggestion to which I was responding was that C/C++
automatically zero out a pointer when you deallocate the memory to which
that pointer refers.
> However, you have the dangling pointer s2, which you must not apply
> the delete operator to again. This will result in at least a
> segmenatation fault.
It *might* segfault---if you're lucky.
> For safety's sake, assign 0 to s2, so it will receive the null
> pointer value.
My point was that *finding* s2 is extremely difficult in the general
case, for the runtime system, the compiler, or the programmer. In fact,
in certain situations, the programmer can't set s2 back to the null
pointer, as it's not in scope at the point of the deallocation (e.g., a
local variable in the function a few levels back up the call stack).