2011-06-28 444 views
3

當使用dlfcn家人像這樣:的dlopen/dlsym進行/ dlclose(dlfcn.h中)導致內存泄露

#include <stdio.h> 
#include <dlfcn.h> 

typedef int(*timefunc_t)(void*); 

int main() 
{ 
    timefunc_t fun; 
    void* handle; 
    handle = dlopen("libc.so.6", RTLD_LAZY); 
    fun = (timefunc_t)dlsym(handle, "time"); 
    printf("time=%d\n", fun(NULL)); 
    dlclose(handle); 
    return 0; 
} 

這會導致內存泄漏:

==28803== Memcheck, a memory error detector 
==28803== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. 
==28803== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info 
==28803== Command: ./dl 
==28803== 
time=1309249569 
==28803== 
==28803== HEAP SUMMARY: 
==28803==  in use at exit: 20 bytes in 1 blocks 
==28803== total heap usage: 1 allocs, 0 frees, 20 bytes allocated 
==28803== 
==28803== LEAK SUMMARY: 
==28803== definitely lost: 0 bytes in 0 blocks 
==28803== indirectly lost: 0 bytes in 0 blocks 
==28803==  possibly lost: 0 bytes in 0 blocks 
==28803== still reachable: 20 bytes in 1 blocks 
==28803==   suppressed: 0 bytes in 0 blocks 
==28803== Rerun with --leak-check=full to see details of leaked memory 
==28803== 
==28803== For counts of detected and suppressed errors, rerun with: -v 
==28803== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 13 from 6) 

我的問題是,這是一個編程錯誤,或者更確切地說是dlfcn/libdl.so中的錯誤?

+0

@jmbr:您應該將其作爲答案發布,以便我可以接受它:-) – hiobs

+0

valgrind是否已經發布了大量與dl類型加載有關的抑制規則?用'-v'再次運行它以查看是否還有更多... –

+0

完成後,我將刪除此處的註釋以避免冗餘。 – jmbr

回答

3

看起來像後者。然而,這看起來不是什麼大問題,因爲如果你重複調用另一個例程的dlopen/dlsym/dlclose,你會發現內存泄漏的大小相同,它不會隨着dlopen/dlclose調用的數量而增長。

+4

另一種說法是,「O(1)'內存泄漏」不是泄漏,而是一滴水。 :-) –

+0

哈哈,我喜歡那樣。 – jmbr