Brutha has asked for the wisdom of the Perl Monks concerning the following question:
after lots of reading (but less understanding) of perlxstut, perlxs, perlguts and Perl XS: garbage-collecting my malloc'd buffer, but I still cannot figure out when to free external allocated memory.
I have an external library, that allocates memory, which i have to free. It returns the pointer in a char* variable, to which I provide an address. So one try of my code looks like this:
The C function fwyPropertyGetChar allocates memory and return it in pValue. I am supposed to free it. Now tye answered in the mentioned thread:void PropertyGet(self, propName) fwyHANDLEobj self char* propName PREINIT: char* pValue; int rc; PPCODE: rc = fwyPropertyGetChar( self, propName, &pValue ); if (rc == 0) { XPUSHs(sv_2mortal(newSVpv(pValue, 0))); # free(pValue); <=== does not work } else { XSRETURN_UNDEF; }
When you tell XS that you have a "char *" input buffer, it pulls out a pointer to the string value (if any) stored in the scalar you pass in. So that buffer is allocated just like any other scalar string value buffer in Perl and is free()d in the same situations. So you don't need to worry about a memory leak.Is that true in my case?
If yes, then I do not understand the line in perlguts (different context though)
that would try to free a constant constant string. Wouldn't it need an strdup then?sv_setpv(sv, dberror_list[dberror]);
On Windows I get "Free to wrong pool 15d2d20 not 80104 at t/07-sample.t line 80" when I uncomment free, but I get this with every pointer that the API gives me, even when it is not converted to Perl variables, e.g pointers hold in a structure that I free in DESTROY.
Any guidelines for freeing external alocated memory in Perl? Thanks in advance.
And it came to pass that in time the Great God Om spake unto Brutha, the Chosen One: "Psst!"
(Terry Pratchett, Small Gods)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XS malloc and free (whose)
by tye (Sage) on Feb 07, 2006 at 17:04 UTC | |
by BrowserUk (Patriarch) on Feb 07, 2006 at 20:07 UTC | |
by tye (Sage) on Feb 07, 2006 at 20:26 UTC | |
by BrowserUk (Patriarch) on Feb 07, 2006 at 20:59 UTC | |
by Brutha (Friar) on Feb 08, 2006 at 07:08 UTC | |
| |
by ikegami (Patriarch) on Feb 07, 2006 at 19:15 UTC | |
by tye (Sage) on Feb 07, 2006 at 20:17 UTC | |
|
Re: XS malloc and free
by Courage (Parson) on Feb 07, 2006 at 16:21 UTC | |
by ikegami (Patriarch) on Feb 07, 2006 at 19:02 UTC | |
|
Re: XS malloc and free
by salva (Canon) on Feb 07, 2006 at 15:23 UTC | |
by Brutha (Friar) on Feb 07, 2006 at 15:35 UTC |