develooper Front page | perl.perl5.porters | Postings from April 2003

[PATCH] Perl_croak("Use of freed value in iteration")

Thread Next
Dave Mitchell
April 21, 2003 05:19
[PATCH] Perl_croak("Use of freed value in iteration")
Message ID:
It's a well-known bug that deleting things while iterating over items
on the stack causes nasty coredumps, eg

    @a = (3,4);
    @a = () for (1,2,@a);

This is because items on the stack aren't ref counted. This is too hard
to fix, but the following patch applies the princple of post-equine-exit-
paddock-area-securing, by giving a fatal error if it iterates over a freed
value. Better a strange warning than a coredump?

PS - I wasn't sure where to put a test - cmd/for.t sounds likely, but
it needs a fresh Perl, so would it be be okay to add "require" in
such a base test file?


My get-up-and-go just got up and went.

--- pp_hot.c-	Mon Apr 21 12:13:39 2003
+++ pp_hot.c	Mon Apr 21 12:38:29 2003
@@ -1859,6 +1859,12 @@ PP(pp_iter)
     else {
 	sv = AvARRAY(av)[++cx->blk_loop.iterix];
+    if (sv && SvREFCNT(sv) == 0) {
+	*itersvp = Nullsv;
+	Perl_croak(aTHX_
+	    "Use of freed value in iteration (perhaps you modified the iterated array within the loop?)");
+    }
     if (sv)
--- pod/perldiag.pod-	Mon Apr 21 12:27:10 2003
+++ pod/perldiag.pod	Mon Apr 21 12:45:23 2003
@@ -4230,6 +4230,18 @@
 generally because there's a better way to do it, and also because the
 old way has bad side effects.
+=item Use of freed value in iteration (perhaps you modified the iterated array within the loop?)
+(F) This is typically caused by code like the following:
+    @a = (3,4);
+    @a = () for (1,2,@a);
+You are not supposed to modify arrays while they are being iterated over.
+For speed and efficiency reasons, Perl internally does not do full
+reference-counting of iterated items, hence deleting such an item in the
+middle of an iteration causes Perl to see a freed value.
 =item Use of reference "%s" as array index
 (W misc) You tried to use a reference as an array index; this probably

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About