Don't ask to ask, just ask | |
PerlMonks |
Re: Perl XS: garbage-collecting my malloc'd buffer (grow)by tye (Sage) |
on Mar 03, 2003 at 17:09 UTC ( [id://240076]=note: print w/replies, xml ) | Need Help?? |
Your original code didn't have a memory leak. [ Update: Rather, it needn't have a memory leak. Just remove the "buffer = (char *)malloc(len);" which I skipped over when I read it. (: ] 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. You could think of your original code as "inconvenient" or even "dangerous" because it requires the caller to pass in length($buffer) or at least a value that is smaller than the size of the buffer allocated to the "buffer" scalar that is passed in. But I'd probably fix that by forcing the scalar to contain a buffer of the specified size before calling the C function: see perlguts for more on SvGROW() (see also perlxstut, perlxs, etc.) (: Updated to match what I'd use based on the feedback below. - tye
In Section
Seekers of Perl Wisdom
|
|