Foreach Access Violation

Steven Schveighoffer schveiguy at yahoo.com
Tue Oct 21 06:13:09 PDT 2008


"nobody" wrote
> /*
> With apples[$-1] = null, without delete this
> <OUTPUT>
> iterate() apples[0]
> iterate() apples[1]
> iterate() apples[2]
> iterate() apples[3]
> die() apples[4]
> iterate() apples[9]
> iterate() apples[5]
> die() apples[6]
> iterate() apples[8]
> iterate() apples[7]
> Error: Access Violation
> </OUTPUT>
> Because of the foreach loop, this access violation makes sense.

Yes, because the foreach still looks at the elements you have removed, so it 
is trying to call a virtual function on a null pointer.

> Without apples[$-1] = null, with delete this
> <OUTPUT>
> iterate() apples[0]
> iterate() apples[1]
> iterate() apples[2]
> iterate() apples[3]
> die() apples[4]
> iterate() apples[9]
> iterate() apples[5]
> die() apples[6]
> iterate() apples[8]
> iterate() apples[7]
> iterate() apples[8]
> iterate() apples[9]
> </OUTPUT>
> Because the array length is changed while in the foreach loop, the last 2 
> lines show up.
> However in my original code this also gives an access violation, and those 
> last lines don't show up.
> So possibly in this example code the delete this doesn't kick in, but in 
> my longer original code it does?
> */

You didn't give your complete original code.  Did per chance the original 
code have a destructor for Apple?  If so, it probably was in the destructor 
that the problem occurred, since the memory was probably being destroyed 
twice.

Note that in destructors, you should not access any references to other 
data, as these might be invalid by the time your destructor is called.  If 
you have nothing but GC-allocated memory, then you should not use a 
destructor.

-Steve 




More information about the Digitalmars-d-learn mailing list