Foreach Access Violation

nobody somebody at somewhere.com
Tue Oct 21 00:54:08 PDT 2008


> You are doing several things in the die function that are very bad.
>
> #1, you shouldn't ever use delete this.
> #1a, you should probably avoid using delete altogether.  That is what the 
> garbage collector is for.

I'm not used to letting a gc handle things, but I guess you're right.

> #2, if you insist on using delete this, you should exit the function 
> immediately afterwards.

In my code I have a break right after that, seems I forgot to type that 
here.

> #3, you are technically not allowed to change the length of the array 
> during foreach, although I don't see why that would cause an access 
> violation.
> #4, you should set apples[$-1] to null, to avoid dangling references to 
> memory so the GC will clean it up, especially if you follow suggestion #1a

Alright, thanks.

>
>>
>> Is this because the foreach loop doesn't reevalute the length of the 
>> apples array
>> while looping, or am I missing something else entirely?
>
> My gut tells me that it's something else.  Even if the loop is not 
> reevaluating length, the memory that it was pointing to is still valid 
> memory, so it shouldn't cause an access violation.  The clue that it's the 
> last apple (BTW, does 'last' mean that there's only 1 element left in the 
> array, or many elements and you are removing the end element?) says that 
> probably it's the delete that's messing up something.  Try printing out 
> information inside the foreach loop to see where the problem lies.

I'm writing some small code to see if I can replicate it. I'll reply with it 
once I do.

>
> But unfortunately, in order to not violate the D spec, you should use a 
> for loop, not a foreach loop.  That is the answer that you probably should 
> follow.

That's what I figured, thanks.

>
> -Steve
> 




More information about the Digitalmars-d-learn mailing list