Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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

by Anonymous Monk
on Mar 31, 2017 at 20:11 UTC ( [id://1186646]=note: print w/replies, xml ) Need Help??


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

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

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

    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.

        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!

Log In?
Username:
Password:

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

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

    No recent polls found