Reputation: 9405
//File A.h containing class A
//DLL or dylib code.
class A {
//Class methods
A ()
{
count = 5;
}
//Append is running fine as it is tested
A& Append (const A& a)
{
//Append operation.
str = str + a.str;
return *this;
}
//this is running fine in all other cases except for this static object.
A& operator= (const A& a)
{
//Statement 1
str = a.str;
//Problem is faced in the statement 1 on the assignment of str to a.str
//I forget to add this code.
count = a.count;
return *this;
}
private:
std::string str;
int count;
};
//File B.cpp in some other layer
//When these variables in dylib.
static A obj1;
static A obj2;
static void f ();
static void g ();
//This Initialize is called whenver DLL or dylib is being loaded.
Initialize ()
{
f();
g();
}
//Problem faced in a function f
void f ()
{
A a;
//Some operation performed on a
a.Append (GetA("String"));
//Here I am facing problem of Bad memory access possibly over statement 1.
obj1 = a;
//Debugger on Windows showing the member of obj1 initialized, but not on Mac OS X.
}
void g ()
{
A a;
//Some operation performed on a
//Here I am facing problem of Bad memory access possibly over statement 1.
obj2 = a;
//Debugger on Windows showing the member of obj1 initialized, but not on Mac OS X.
}
//The application An exe or .app on Mac OS X
int main ()
{
InitializeApplication ();
void * handle;
//Dynamic library is being loaded.
handle = dlopen("mylib.dylib", RTLD_LAZY);
//Functions are being loaded.
f1 = dlsym(handle, "MyFunction");
//Rest of the code.
}
When I run a similar program on Windows (compiled using cl compiler), the value obj1.count and obj2.count are 5 (as initialized by default constructor).
However, when I run this program on Mac OS X (compiled using clang compiler), the value of obj1.count and obj2.count are 0.
Am I missing something to initialize static object of a class? What are the steps required if there is an array?
In my program, there is an application loading a dylib (on Mac OS X) or DLL (on Windows). This code is the part of shared library or DLL.
Static object obj1 and obj2 are in DLL. This DLL is being loaded and then called.
Following behaviour is observed in Windows
On Mac OS X
On Mac OS X, everything in the object is initialized by Zero. Every address is NULL.
However, when I moved these variables to a static library (which is linked to this dylib), then everything is running as per the expecation.
Is there any issue of global/static objects in dylib?
Upvotes: 0
Views: 922
Reputation: 129374
Since your:
A& operator= (const A& a)
{
//Statement 1
str = a.str;
}
doesn't copy count
, then we can expect "undetermined" value of count
in the copied object. Which may of curse be 5
, but also some other value. The operator=
should copy (or otherwise initialize) ALL the contents of the class.
Edit: And you should have a return *this;
in there too.
Upvotes: 1