Foreach Access Violation

nobody somebody at
Tue Oct 21 01:00:55 PDT 2008

"BCS" <ao at> wrote in message 
news:78ccfa2d3408b8cb00ab37d623b8 at
> Reply to nobody,
>> Apple[] apples;
>> for(int i = 0; i < 10; i++)
>> {
>> apples.length = apples.length + 1;
>> apples[apples.length-1] = new Apple();
>> }
> Apple[] apples = new Apples[10];
> for(int i = 0; i < 10; i++)
> {
>  apples[apples.length-1] = new Apple();
> }
> The above would be faster in many cases. Extending length often results in 
> a new allocation and must check to see if it needs to do one every time.
> If I just want to accumulate things but don't know in advance how many 
> there will be I over allocate by a bit, keep track of how many you have 
> used externally and slice it back down once your done.

I guess that's possible, but it would only speed up the init of a few 
hundred apples.
After that while it's running it only deletes or adds about 1 to 5, so 
calculating a new allocation every time would not provide much of a boost.
Right now I'm not too concerned with that initial speed boost, but thanks 
for the tip.

>> This generally works fine, except when the last apple is deleted.
>> Then I get an Access Violation Error in the foreach loop.
>> When I use a for loop instead it works perfectly.
>> Is this because the foreach loop doesn't reevalute the length of the
>> apples
>> array
>> while looping, or am I missing something else entirely?
> IIRC the docs say is it illegal to alter the loop array inside of a 
> foreach

Alright, thanks. 

More information about the Digitalmars-d-learn mailing list