Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Wrapping a C shared library with Perl and XS

by Anonymous Monk
on Mar 28, 2017 at 16:21 UTC ( [id://1186270]=note: print w/replies, xml ) Need Help??


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

It might be worth pointing out for other readers that after arr() returned a malloced array and you have handled its contents it's your XS code's obligation to free() it. Otherwise, this code would have a memory leak.

Replies are listed 'Best First'.
Re^2: Wrapping a C shared library with Perl and XS
by stevieb (Canon) on Mar 28, 2017 at 16:35 UTC

    ohhh, right! I completely forgot about that :)

    Thanks for pointing it out!

Re^2: Wrapping a C shared library with Perl and XS
by stevieb (Canon) on Mar 29, 2017 at 03:31 UTC

    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 ;)

      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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-25 10:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found