develooper Front page | perl.perl5.porters | Postings from June 2016

Re: [perl #127759] die inside sort comparitor causes SV error

Thread Previous | Thread Next
From:
Dave Mitchell
Date:
June 7, 2016 15:04
Subject:
Re: [perl #127759] die inside sort comparitor causes SV error
Message ID:
20160607150433.GC3167@iabyn.com
On Mon, Mar 21, 2016 at 03:20:31PM -0700, via RT wrote:
> # New Ticket Created by   
> # Please include the string:  [perl #127759]
> # in the subject line of all future correspondence about this issue. 
> # <URL: https://rt.perl.org/Ticket/Display.html?id=127759 >
> 
> 
> 
> This is a bug report for perl from jim.avera@gmail.com,
> generated with the help of perlbug 1.40 running under perl 5.20.2.
> 
> 
> -----------------------------------------------------------------
> If die is called inside a sort comparitor function, errors like the
> following (sometimes) occur.
> 
>   Attempt to free unreferenced scalar: SV 0x12c7458, Perl interpreter: 0x12a2010 at (location of die)
> 
> 
> #!/usr/bin/perl 
> use warnings; use strict; use 5.010;
> 
> my @data = ( ["A"], ["B"], ["C"] );
> 
> @data = 
>   sort {
>     my $aval = $a->[0];
>     my $bval = $b->[0];
> 
>     die "Die in sort comparator" if $aval eq "C"; 
> 
>     return ($aval cmp $bval);
>   }
>   @data;
> 
> # Die in sort comparator at /tmp/test.pl line 11.
> # Attempt to free unreferenced scalar: SV 0x12c7458, Perl interpreter: 0x12a2010 at /tmp/test.pl line 11.
> # Attempt to free unreferenced scalar: SV 0x12c7450, Perl interpreter: 0x12a2010 at /tmp/test.pl line 11.
> # 

This is an interaction between sort's 'in place' optimisation, and perl's
implementation of the mergesort algorithm.

In something like

    @a = sort {...} @a,
    
where the same array is on both sides, the assign is optimised away and
sort() just sorts the array of SV pointers in @a's AvARRAY() directly.
But it turns out that (AFAIKT) S_mergesortsv() temporarily stores random
pointers in sort slots (rather than only pointers to the SVs being
sorted).  If the compare sub dies in mid-sort, random rubbish gets left in
the AvARRAY array, which then causes crashes when the array falls out of
scope.

The merge sort code is a bit impenetrable, so I'm unsure as yet of the
best way to fix this.


-- 
A major Starfleet emergency breaks out near the Enterprise, but
fortunately some other ships in the area are able to deal with it to
everyone's satisfaction.
    -- Things That Never Happen in "Star Trek" #13

Thread Previous | 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