On 2004-10-01, at 09:50:33 +0100, Steve Hay wrote: > Why does the following XS code leak? > > #include "EXTERN.h" > #include "perl.h" > #include "XSUB.h" > > typedef struct { > char *buf; > } Foo; > > Foo *FooAlloc(pTHX) { > Foo *foo; > New(0, foo, 1, Foo); > New(0, foo->buf, 1024, char); > return foo; > } > > void FooFree(pTHX_ Foo *foo) { > Safefree(foo->buf); > //Safefree(foo); > } > > MODULE = Foo PACKAGE = Foo > > void > foo() > PPCODE: > { > SV *sv; > Foo *foo; > sv = NEWSV(0, 0); > foo = FooAlloc(aTHX); > sv_usepvn(sv, (char *)foo, sizeof *foo); > SvPOK_only(sv); > SvREADONLY_on(sv); > FooFree(aTHX_ foo); > SvREFCNT_dec(sv); > } > > The Safefree(foo) is commented out in FooFree() because I believe that > sv_usepvn() has reallo()'ed foo and will free() it for me when sv's > refcount becomes 0. I tried uncommenting the Safefree(foo) to see if it > made any difference, but it still leaks. > > The leak is easily seen just by building a Foo module out of the above > and running > > perl -Mblib -MFoo -e "<STDIN>; for (1 ..10000) { Foo::foo() } <STDIN>;" > > If I comment-out the sv_usepvn() call, and accordingly restore the > Safefree(foo) once more, then the XSUB doesn't leak.
Mmmmh, I cannot reproduce any leaks on Linux with 5.8.4 or blead. Which version of Perl are you using? Which OS (I'm guessing Win32)? Any special configuration? Marcus -- Steinbach's Guideline for Systems Programming: Never test for an error condition you don't know how to handle.