0

I have a class consisting purely of class statics in one .so, which gets called from various other .sos, but on program exit under valgrind I get a double free error that says:

==23162== Invalid free() / delete / delete[] / realloc()
...
==23162==  Address 0xe187d70 is 0 bytes inside a block of size 97 free'd
...
==23162==  Block was alloc'd at
....
==23162==    by 0x165C0C90: FileManager::setCommonConfigFolder(...)
             (in .../lib2.so)

The code is actually in lib1.so, but called from lib2.so.

Looking around, I see this answer:

No it is not shared - the code/text section of the library is shared - the data portion is unique to each process that uses the library

So what is the timing for freeing static objects allocated by the actions of the client of the library? How do I avoid this problem?

The relevant portions of the code are as follows. This is compiled into lib1.so and called from lib2.so and lib3.so. With suitable logging, I can see that the address in the valgrind report Address 0xe187d70 is 0 bytes inside a block of size 97 free'd is indeed mCommonConfigDirectory.data.

FileManager.cpp

#include "FileManager.h"
#include <string>

std::string FileManager::mCommonConfigDirectory = "../common/config";

void FileManager::setCommonConfigFolder (std::string const& configPath)
{
    mCommonConfigDirectory = configPath;
}

FileManager.h

#include <string>

class FileManager
{
public:
    static void setCommonConfigFolder (std::string const& configPath);

protected:
    static std::string mCommonConfigDirectory;
};
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • 1
    post [mcve] please – xaxxon Apr 08 '19 at 03:35
  • "I have a class consisting purely of class statics". That would probably be a design error, but it doesn't by itself cause a double freeing. You need to find out where the block was freed the first time. – n. m. could be an AI Apr 08 '19 at 03:58
  • @n.m. In my defense, I inherited the code. The memory appears to be freed once for each `.so` that uses it. So does that imply that the class statics end up in a separate section that loads only once along with the code and text, not multiple times with the data for the processes that use the library? But that doesn't fit with what I am observing... – Ken Y-N Apr 08 '19 at 04:25
  • Hmm, I made my class [into a singleton](https://stackoverflow.com/a/1008289/1270789) and the problem goes away, and the addresses of `mCommonConfigDirectory.data` looks much better. – Ken Y-N Apr 08 '19 at 04:57
  • "The memory appears to be freed once for each .so that uses it" This is not supposed to happen. Either there's one copy of the variable, and it gets destroyed once; or there are multiple copies at different addresses, and they don't interfere with each other. – n. m. could be an AI Apr 08 '19 at 05:08

0 Answers0