では、メモリを割り当ててポインタを返す IC/C++ コードを考えてみましょう。
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
void Allocate(void **p) {
int N=2048;
*p=malloc(N);
}
#ifdef __cplusplus
}
#endif
明らかに、そのメモリブロックを解放するのは私の責任だと思っています。これを共有ライブラリにコンパイルし、ctypes を使用して Python から呼び出しますが、そのメモリを明示的に解放しないとします。
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))
このスクリプトを valgrind で実行すると、'-O3' フラグを指定せずに test.cpp をコンパイルすると、2048 バイトのメモリ リークが発生します。しかし、「-O3」フラグを付けてコンパイルすると、メモリ リークは発生しません。
それは実際には問題ではありません。割り当てたメモリを明示的に解放するよう常に注意しています。しかし、私はこの行動がどこから来たのか興味があります。
Linuxで次のスクリプトを使用してこれをテストしました。
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 &> report1
valgrind python test2.py &> report2
次の出力で
レポート 1:
==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
レポート 2:
==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