Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: garbage collector behavior with ctypes
    primarykey
    data
    text
    <p>So let's say I C/C++ code that allocates some memory, and returns a pointer to it.</p> <pre><code>#include &lt;stdlib.h&gt; #ifdef __cplusplus extern "C" { #endif void Allocate(void **p) { int N=2048; *p=malloc(N); } #ifdef __cplusplus } #endif </code></pre> <p>I'm expecting that it's my responsibility to free that block of memory, obviously. Now suppose I compile this into a shared library and call it from Python with ctypes, but don't explicitly free that memory.</p> <pre><code>import ctypes from ctypes import cdll, Structure, byref external_lib = cdll.LoadLibrary('libtest.so.1.0') ptr=ctypes.c_void_p(0) external_lib.Allocate(ctypes.byref(ptr)) </code></pre> <p>If I run this script with valgrind, I get a memory leak of 2048 bytes if I compile test.cpp without the '-O3' flag. But if I compile it with the '-O3' flag, then I do not get the memory leak. </p> <p>It's not really a problem - I'll always be careful to explicitly free any memory I allocate. But I'm curious where this behavior comes from.</p> <p>I tested this with the following script in linux.</p> <pre><code>g++ -Wall -c -fPIC -fno-common test.cpp -o libtest1.o g++ -shared -Wl,-soname,libtest1.so.1 -o libtest1.so.1.0 libtest1.o g++ -O3 -Wall -c -fPIC -fno-common test.cpp -o libtest2.o g++ -shared -Wl,-soname,libtest2.so.1 -o libtest2.so.1.0 libtest2.o valgrind python test1.py &amp;&gt; report1 valgrind python test2.py &amp;&gt; report2 </code></pre> <p>with the following output</p> <p>report1:</p> <pre><code>==27875== LEAK SUMMARY: ==27875== definitely lost: 2,048 bytes in 1 blocks ==27875== indirectly lost: 0 bytes in 0 blocks ==27875== possibly lost: 295,735 bytes in 1,194 blocks ==27875== still reachable: 744,633 bytes in 5,025 blocks ==27875== suppressed: 0 bytes in 0 blocks </code></pre> <p>report2:</p> <pre><code>==27878== LEAK SUMMARY: ==27878== definitely lost: 0 bytes in 0 blocks ==27878== indirectly lost: 0 bytes in 0 blocks ==27878== possibly lost: 295,735 bytes in 1,194 blocks ==27878== still reachable: 746,681 bytes in 5,026 blocks ==27878== suppressed: 0 bytes in 0 blocks </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload