A bug in my code

Sergey Gromov snake.scaly at gmail.com
Mon Sep 8 14:55:15 PDT 2008


bearophile <bearophileHUGS at lycos.com> wrote:
> - That particular stack implementation is designed for ints only, so 
> they don't contain references, so that code works (It seems).
> - But you are right, if the data block contains references then the 
> realloc(... ,0) are very bad.

Your code will work with arrays of pointers either.  The potential 
problem is not in array elements pointing somewhere else, but in some 
external references pointing into your array.  Well, since your code 
guarantees that such external references are impossible, it always works 
as expected.

> - So generally in such programs the right thing to do seems to not 
> dealloc memory, but remove the known references to it, and then let the 
> GC deallocate such memory when it can't find references pointing to that 
> memory.

It's the safe thing to do.

> - Yet, I have seen that for some data structures (probably ones with 
> long chains of references) letting the GC do all the work of looking for 
> unconnected components to deallocate them leads to long destruction 
> times (2-10 seconds of time in one case). In such situations I think it 
> may be better to give the GC a hand, actually deallocating the data 
> structure inside the destructor using an efficient algorithm (if the 
> programmer is sure it doesn't contain references to other allocate data) 
> (this needs just few hundreds of seconds in the same case of before).

My apologies.  Your last code was correct.  It was just dangerous, as 
any other explicit memory management code is.  The danger was in that it 
was easy to make breaking changes to your code and not notice.  My 
variant was simply safer but also probably slower under some 
circumstances.

Hugs.


More information about the Digitalmars-d-learn mailing list