Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: Wrapping a C shared library with Perl and XS

by stevieb (Canon)
on Mar 29, 2017 at 03:31 UTC ( [id://1186300]=note: print w/replies, xml ) Need Help??


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

It is honestly a bit elusive to me exactly how and when to free() within the XS in the case I've shown explicitly, but using the same repo I used to generate this example tutorial, I'm going to play around a bit here.

I will post back here and update my OP once I figure it out.

As always, feedback welcome ;)

Replies are listed 'Best First'.
Re^3: Wrapping a C shared library with Perl and XS
by Anonymous Monk on Mar 31, 2017 at 20:11 UTC

    One of the approaches to freeing memory is to call free right after the last usage of a pointer (in our case it's the loop which calls inline_stack_push(sv_2mortal(newSViv(c_array[i])));) and set it to NULL afterwards.

    Setting a pointer to NULL serves double purpose:

    1. Checking for NULL is very easy, checking if non-NULL pointer is valid is very complex at best
    2. If you defensively call free(c_array) in another part of the program, free(NULL) would be safe on modern libcs, while free of a freed pointer causes memory corruption

      Thank you very much AnonyMonk!

      I especially appreciated the fact you used the term "our" in your reply, as it shows that even Anonymous Monk cares and has interest ;)

      I'll pull this back out over the weekend sometime and play around with it and run things against valgrind.

      Your feedback is appreciated in my curve of learning. I'll update the OP after I've played around.

        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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1186300]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-25 13:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found