in reply to Re^4: Wrapping a C shared library with Perl and XS
in thread Wrapping a C shared library with Perl and XS

I'll pull this back out over the weekend sometime and play around with it and run things against valgrind.
I'm not sure about properly written libperl applications (i.e. ones creating PerlInterpreter objects and not forgetting to call perl_destruct(my_perl); perl_free(my_perl); PERL_SYS_TERM(); afterwards), but perl itself is known to show leaks when checked by valgrind. As in,
$ valgrind perl -e1 2>&1 | grep definitely ==12501== definitely lost: 7,075 bytes in 15 blocks

Part of the reason for that might be to speed up termination: why bother calling free() if the process is going to die right now and the OS will pick up its resources anyway? But there are other possible reasons for valgrind to report a memory leak.

Replies are listed 'Best First'.
Re^6: Wrapping a C shared library with Perl and XS
by stevieb (Canon) on Apr 08, 2017 at 03:34 UTC

    I still haven't got back to this yet, but I'm re-raising now that I'm back home to look into it.

    Thanks for the deep insight!

      Sorry for nudging you again, but I think that this needs to be fixed, because this tutorial is intended for people with little knowledge of XS and C, and memory management is one of the aspects in which Perl differs greatly from C. It's quite easy to imagine someone being too used to reference counting of Perl to think that in C, allocated memory should be manually returned to OS.

      Maybe it's just me, bitten by segfaults, memory corruption and leaks almost every time I write in plain C. And tutorial code is inevitably copied without much incentive to change it, since it produces the right output...

      And the fix is simple: a free(c_array); inserted between the for (i=0; i<3; i++) {/*...*/} loop (which uses the pointer) and inline_stack_done; (which cleans up at the end of void _arr). A real world library in place of xswrap example would probably document that the pointer returned by unsigned char * arr(void) fully belongs to the user and needs to be freed after use.

        Thanks for the reminder... I had completely forgot about this. Your recommended fix has been edited into the post.