Suppose I have an shared library file (say libtemp.so) which has a global variable. If I dynamically load this library, assign a heap memory to it, and then close the library. If I load the library again, then is the old heap memory leaked? (I think its true since global variables will be reset when the library is loaded again)
Is it a bad practice to assign heap memory to a global variable? Are there any cases where we end up having to do this?
On Linux, the library global variable sits in some data segment of the shared object, and that segment would have been
munmap-ed whendlclose-ing thelibtemp.soand would have beenmmap-ed again at the nextdlopenso the global would have been reinitialized.(I am assuming you are doing only one single
dlopeni.e. that thelibtemp.sois notdlopen-ed twice)BTW, you could do initialization in constructor functions (and finalization in destructor), see function attributes in GCC. The constructors are executed at
dlopentime, and the destructors atdlclosetime. Read also Linux dlopen(3) man page for details. (Notice that POSIX dlopen don’t have these tricks)