#!/usr/bin/perl
#
# Perl script to demonstrate Perl segfault bug.  The good() subroutine runs, 
# apparently regardless of how many tokens are created.  The bad() subroutine
# segfaults when the number of tokens is greater than ~30,000.  The precise
# number varies depending on platform and version of Perl.
#
# Written by Andy Wardley http://wardley.org/
#
# 03 November 2009
#

use strict;
use warnings;

my $max = shift || 40_000;

print "starting\n";

good($max);
bad($max);

print "finishing\n";


sub good {
    my $max  = shift;
    my $n    = 0;
    my ($token, $last);

    print "creating linked list of $max tokens\n";

    while (++$n < $max) {
        $token = ["token $n"];
        $last->[1] = $token if $last;
        $last = $token;
    }

    print "created $max tokens\n";
}


sub bad {
    my $max = shift;
    my $n   = 0;
    my (@tokens, $token, $last);

    print "creating linked list of $max tokens in container\n";

    while (++$n < $max) {
        $token = ["token $n"];
        $last->[1] = $token if $last;
        $last = $token;
        push(@tokens, $token);
    }

    print "created $max tokens\n";
}


