Reputation: 103
I have a base and a derived class:
In A.h:
//Includes
class A {
protected:
static std::string a;
//other dummy code
};
In A.cpp
std::string A::a = "bar";
//other dummy code
In B.h:
#include "A.h"
//Other includes
class B : public A {
public:
int c;
//other dummy code
};
Main.cpp:
#include "A.h"
#include "B.h"
int main() {
printf("foo");
return 0;
}
Now I compile A.cpp and B.cpp into two separate shared libraries as "a.so" and "b.so" and then link them against Main.cpp. When I run the program - it quits with corrupted-double-linked list error. Running with valgrind I see that there is an invalid free error. Why does this happen?
I understand that each .so file must have its own copy of static global variables, but what happens when a derived class is in a different shared library while the base class is in a different shared library and there are static variables in the base class? How memory is allocated/destructed for the static variables in base class, across libraries where derived classes are present?
Upvotes: 1
Views: 1295
Reputation: 44268
I understand that each .so file must have its own copy of static global variables
You understand incorrectly, unless you linked A.o into both a.so and b.so each .so file will not have it's own copy of static A::a. A.o should only be linked to a.so and b.so shoould be linked with a.so, not A.o
Upvotes: 2