I stumbled across a problem from nowhere.
Suddenly my project that I am working on stopped working. I'm using Xcode 5.1.1 (LLVM 3.4, clang 5.1). The issue is that most static variables doesn't get initialized anymore at startup.
I didn't change anything which could lead to this problem but I'm curious to know what could have caused it and possibly how to solve it.
I'm talking about simple situations like:
// File.h
class MyClass {
static std::vector<MyObject*> data;
}
// File.cpp
std::vector<MyObject*> MyClass::data;
By running the program I get a length exception when trying to add elements to the vector, to realize that its size is just a garbage value. This happened to other static fields in other files with no apparent reason. The code itself is not used as a library but compiled as it is, and it worked flawlessly so far.
EDIT: building the release scheme doesn't show the problem, just to add more unpredictability.
EDIT: Things are even weirder than I expected. Another static variables which I manually initialized doesn't work too. The offending code is the following:
// .h
class MyClass {
static MyClass* i;
public:
static void init();
static MyClass* getInstance();
}
// .cpp
MyClass* MyClass::i;
void MyClass::init() { i = new MyClass(); }
MyClass* getInstance() { return i; }
Now if I watch the values of i
after the init()
is called and when getInstance()
is used for the first time I get two different addresses:
(lldb) p MyClass::i
(MyClass *) $0 = 0x09e36a50
(lldb) p MyClass::i
(MyClass *) $1 = 0x00620000
And I don't get how this is possible since (init()
) is called just once (and before (getInstance()`)
std::vector
) but this is true for the other cases I found too.static
variables used so far in the code show the same behavior.memcpy
or similar, clobbering unrelated variables? Does your debugger support breaking on data changes? If so, you could set a regular breakpoint onMyClass::init
, and after that finishes, break wheni
changes, and get a stack trace at that time.