1

I use dlopen to load a dynamic library say "lib1.so" and call one exposed function say A1, A1 function allocate a dynamic memory of 100kb using malloc but not deallocate that, in the main function again I all dlclose. [dlopen, call function A1 , dlclose]

I repeate the step say 10 times, Purify report this as memory leak of 1000KB , valgrind reports Indirectly lost 1000KB.

Could you please suggest 100 KB * 10 times = 1000KB , Is a real memory leak? As I have called dlclose, so all memory allocated for dynamic libs are automaticaly freed when we call dlclose?

OS: Linux Programming lan : C

4

3 回答 3

5

dlclose不会释放分配给malloc. 它只释放库中声明的静态变量。您应该显式释放库中任何已分配的内存,可能在_fini函数中。

于 2011-10-31T14:39:12.807 回答
3

dlclose 的手册页没有说明在调用时释放内存。

dlclose()
   The  function  dlclose()  decrements the reference count on the dynamic
   library handle handle.  If the reference count drops  to  zero  and  no
   other  loaded  libraries use symbols in it, then the dynamic library is
   unloaded.

   The function dlclose() returns 0 on success, and nonzero on error.

没有魔法。

如果您使用的是 linux,您可以尝试这种方法来包装 malloc() 并跟踪分配的内存。

于 2011-10-31T14:36:50.997 回答
2

不,内存在进程终止时回收,而不是在动态库关闭时回收。

于 2011-10-31T14:37:27.893 回答