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

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

Thread Next
From:
Dave Mitchell
Date:
April 21, 2003 05:19
Subject:
[PATCH] Perl_croak("Use of freed value in iteration")
Message ID:
20030421121950.GB18189@fdgroup.com
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 test.pl" in
such a base test file?

Dave.

-- 
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)
 	SvTEMP_off(sv);
     else
--- 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


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About