std::function and shared object libraries

Jonathan Wakely
Wed Jun 17 08:35:00 GMT 2015

On 17 June 2015 at 00:42, Nick wrote:
> On Tue, 2015-06-16 at 14:06 +0100, Jonathan Wakely wrote:
>> On 16 June 2015 at 13:43, Nick wrote:
>> > By "disappears" I assume you mean the contents of the space are gone,
>> > not that the actual address space is removed, correct?
>> I don't understand the distinction. What does "the actual address
>> space is removed" mean?
> By "removed" I get the impression that it's somehow literally gone.  For
> example, a 4GB address space is now 3GB.  The address space is still
> there, it just contains undefined content which naturally will lead to
> undefined behavior if accessed.

Maybe it's just another problem with terminology but I would say it's
literally gone. After the dlclose() there is nothing mapped at the
address stored in the function pointer f._M_manager. It's not just
garbage memory that produces undefined behaviour, it is not even a
valid address. Trying to access that address causes a segmentation
fault, raised by the operating system, because that address is not
part of the process' virtual address space.

On GNU/Linux you can dump the contents of the /proc/[pid]/maps file to
see the process' memory maps, and you will see that after dlclose()
the address regions previously associated with the shared library are
no longer there.

You can also use top(1) or ps(1) and you will see that the VIRT or VSZ
column shows the total amount of  virtual memory used by the process
is smaller after dlclose().

>> >  So in the case
>> > of the OP, that would amount to allocated objects (ex. function
>> > template)
>> Template instantiations are not allocated. They are code, not data.
> Right, in the case of a basic C++ function template.  From the OP I was
> thinking about something like std::function which I'd expect (though I
> didn't look at the implementation) has some data along with it.

But the problem has nothing to do with that data. The data is in the
program's stack or heap, which doesn't disappear when you dlclose()
the shared library. What disappears is the code for the function that
the object will invoke from its destructor.

This never had anything to do with memory allocation or where
variables live in memory, only code.

More information about the Gcc-help mailing list