[Issue 10876] foreach and remove over associative array causes invalid data to appear

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Aug 23 14:12:00 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=10876


hsteoh at quickfur.ath.cx changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |hsteoh at quickfur.ath.cx


--- Comment #2 from hsteoh at quickfur.ath.cx 2013-08-23 14:11:55 PDT ---
Modifying a container that you're iterating over has undefined results, because
you're iterating over a set of keys that changes from under you as you go. In
the case of AAs, you may end up dereferencing invalid pointers.

The safe way to do it is to get an array of keys and iterate over that:

    foreach (k; aa.keys) {
        auto value = aa[k];
        ...
        if (...)
            aa.remove(k);
    }

N.B. you can only use .keys, not .byKey, because the latter also amounts to
walking the data structure while it is being modified, which will cause
problems. Using .keys is OK because it creates an array of keys (a snapshot of
the set of keys at that point in time) before starting to modify the data
structure.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list