그래서 메모리를 할당하고 포인터를 반환하는 C/C++ 코드를 가정 해 보겠습니다.파이썬 : ctypes를 사용한 가비지 컬렉터 동작
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
void Allocate(void **p) {
int N=2048;
*p=malloc(N);
}
#ifdef __cplusplus
}
#endif
분명히 그 메모리 블록을 해제해야 할 책임이 있습니다. 이것을 공유 라이브러리로 컴파일하고 ctypes로 파이썬에서 호출한다고 가정하되, 명시 적으로 그 메모리를 해제하지는 마십시오. 내가 Valgrind의이 스크립트를 실행하면 나는 '-03'플래그없이 Test.cpp에 컴파일하는 경우
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))
, 나는 2048 바이트의 메모리 누수를 얻을. 하지만 '-O3'플래그로 컴파일하면 메모리 누수가 발생하지 않습니다.
정말 문제는 아닙니다. 할당 한 메모리를 명시 적으로 해제하는 데 항상주의해야합니다. 그러나 나는이 행동이 어디에서 유래하는지 궁금하다.
나는 이것을 리눅스에서 다음 스크립트로 테스트했다. 다음과 같은 출력
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
report2 :
==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
나는 당신의 단계를 수행 한 결과는 흥미 롭다. 'Python 3.3.2'에서 두 개의 보고서는 모두 2048 바이트의 누출을 제공하지만,'Python 2.7.5'에서는 어느 쪽의 보고서에서도 누출이 없습니다. 'Linux 3.11.4 x86_64'에서'gcc 4.8.1 20130725'로 테스트되었습니다. – starrify