I know that dynamic loaded libraries share the same address space but I'm not sure what happens when I allocate memory in a dynamically loaded library and close the library. Is the allocated object still valid when the object is not a part of the loaded library? For example a simple std::string or any of my classes?
(I am taking a Linux point of view; the C++14 standard don't know about dynamic loaded libraries)
There is only one single heap (and a single virtual address space) for the entire process running your C++ program. So at the low level a memory zone can be allocated from one library lib1.so and freed from another one lib2.so - in the same process.
You can have several processes using the same shared library; then the text or code segment of that library is effectively shared (but not the data segments) between several processes.
The rest is programming convention. The rule of five (before was rule of three) is a very useful convention in C++
Internally, mmap(2) is used, and the address space can be seen with /proc/$PID/maps (see proc(5)). So for a process of pid 1234 try running cat /proc/1234/maps in a terminal, you'll understand more how shared libraries are loaded in the virtual address space of that process.
Is the allocated object still valid when the object is not a part of the loaded library?
Maybe.
On a UNIX system, a heap-allocated object that does not contain any pointers into the loaded library will certainly be valid (because heap is a process-global resource).
However, in C++, a heap-allocated object may contain a virtual table pointer, which will point to .code in the shared library, and if such library is completely unloaded, this virtual table pointer would become invalid. The object would still be addressable, and you could access its data and non-virtual methods, but an attempt to call virtual method will likely crash.
On a Windows system, a DLL can be linked with a shared C runtime MSVRT.DLL, or with a "local" copy of C runtime (LIBCMT.LIB, etc.). More info here. As that page explains, when using statically-linked CRT, resources allocated from it (including heap) are local to this DLL. In particular, unloading such DLL will destroy heap-allocated objects that were allocated from that DLL heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With