in reply to Re: An obscure side effect?
in thread An obscure side effect?
Interesting. I did think about the order of execution thing, and whether that might be the cause, but then I tried this.
#! perl -slw use strict; sub swab{ substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) ^= substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) } my $s ='AB'; swab( $s, 0, 1 ); print "'$s'"; my $t ='AB'; swab( $t, 0, 1 ); print "'$t'"; eval q[ sub swab{ substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) ^= substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) } ]; my $u = 'AB'; swab( $u, 0, 1 ); print "'$u'"; swab( $u, 0, 1 ); print "'$u'"; __END__ P:\test>junk 'BA' ' A' Subroutine swab redefined at (eval 1) line 2. 'BA' ' B'
By redefining swab(), the behaviour goes back to the original, expected result for the first time I call it, with a second and any subsequent calls to the redefined swab() producing erroneous effects.
Then I tried this
#! perl -slw use strict; sub swab1{ substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) ^= substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) } sub swab2{ substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) ^= substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) } my $s ='AB'; swab1( $s, 0, 1 ); print "'$s'"; swab2( $s, 0, 1 ); print "'$s'"; my $u = 'AB'; swab1( $u, 0, 1 ); print "'$u'"; swab2( $u, 0, 1 ); print "'$u'"; __END__ P:\test>junk 'BA' 'AB' ' A' ' '
This shows that both instances of the routine produce the correct result the first time they are called, but then erroneous effects the second time.
This suggests to me that there is an uninitialised piece of memory being used somewhere that was probably initialised to \0 by the malloc or memset that allocated the larger pool of memory from which it was suballocated, but when the routine is called a second time, the same piece of memory is being reallocated from the same pool, but now has whatever last value it contained. Perhaps it is just a C auto that is being allocated on the stack and happens to have a zero in it the first time it is called, but retains the last value it had the next time it gets used?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: An obscure side effect?
by sgifford (Prior) on Aug 04, 2003 at 06:25 UTC | |
by BrowserUk (Patriarch) on Aug 04, 2003 at 07:24 UTC | |
by sgifford (Prior) on Aug 04, 2003 at 07:41 UTC | |
by BrowserUk (Patriarch) on Aug 04, 2003 at 11:36 UTC |