C++ calling a static function from another static function - c++

have a static function in a header file
class Diagnostics {
public:
static void functionA(){
}
static void functionB(){
some code //works fine until enters the loop below
variable_name // works fine here.
if (condition){ //
variable_name; // after condition is met , i step in here, debugger cannot examine
// the vairable_name which was fine above. right after i try to step over , i get SIGSEV error
some_code; // doesnt even come here. Process exited with SIGSEV
function C(); // tried using classname::functionC , didnt work either
}
}
static void functionC(){
}

static inside a class means that the member or method in question does not operate on an object, i.e. it doesn't define this, but it is still in the class's namespace.
static outside a class means what it means in C: the variable or function does not have external linkage, i.e. things outside the current compilation unit cannot link to it.
Two entirely different things.

I dont know the problem was.
Works fine now. initially happened while I was debugging.
Then i just executed instead of debugging , worked fine.
then i tried debugging again , which worked fine this time.

Related

Extern pointer is null in static library, worked fine when not a static library

I broke my Visual Studio project (2015, C++) into three pieces:
The main application in a static library
The executable which just has a main function
Unit tests which use the static .lib file so that they can import the required classes and do the unit tests on them.
Before I split it into a lib/exe/tests, the main application was just a standalone executable, and it worked perfectly fine.
Now I can't run the executable with only the main function, nor the unit tests as a certain pointer is always null. The only main difference is that I'm using a raw pointer in this example, but I was using a unique_ptr in my code (currently however I switched to the raw pointer just to make sure this following example is as accurate as possible and it didn't magically compile/run properly with the raw pointer).
The code looks very similar to the following (the extra code has been removed):
// console.hpp
extern Console *console;
The implementation cpp file (only of what is needed):
// console.cpp
Console *console = new Console();
Now in some unrelated function, this code fails due to the console pointer being a nullptr:
// some_other_file.cpp
#include "console.hpp"
// Inside some function...
console->doSomething(); // console is NULL
Again, the code I have worked perfectly fine when it was in one project. Regardless, it all compiles fine with no linking errors even though it has been broken into 3 pieces, but now that pointer is always null.
As a last interesting note, the non-pointer variables that are global and extern do work. Is this something limited to pointers/unique_ptrs?
Is this something fixable by a singleton pattern?
The clue is in this comment: "it appears other code is getting called before the main function that don't let the global variable get initialized."
The code referencing console is probably running as part of the initialization of another global and, in this case, is happening before the initialization of console. You have to be very careful to be sure that you're not depending on the order of the global initializers. You were probably getting lucky before you split the program, and now your luck has run out.
The easiest way to fix it is to use a singleton pattern. Instead of having other parts of the program directly reference the pointer, you have them call a function that returns the pointer, and that function will initialize it the first time. This ensures that it's initialized before it's used.
Here's a common pattern for it:
Console *GetConsole() {
static Console *console = new Console();
return console;
}
Now console is no longer a global variable. Everything that wants to access the console calls GetConsole instead.
The function-local static variable will be initialized the first time the function is called, and after that it just returns the value. If you have multiple threads and an older compiler, you have to do more work to protect against a possible race condition. Modern compilers should do the initialization in a thread-safe way.

Static initialization of variables fails

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()`)
When you declare statically-scoped objects in different translation units, their relative order of construction is unspecified.
If, for example, you're trying to use MyClass::Data from code that runs as part of a constructor for some other statically-scoped object, in some other translation unit, it's not specified whether or not MyClass::Data is going to get constructed before or after the other statically-scoped object's constructor. If that code that accesses MyClass::Data gets invoked, and MyClass::Data is not constructed yet, that's obviously undefined behavior.
In most common C++ implementations, the order of construction depends upon what the linker does to piece together the final executable; and it is perfectly possible that various changes to your overall application now resulted in the linker stiching together the different object modules in a different order, and changing the relative construction order of statically-scoped objects.
Many implementations provide implementation-specific mechanisms to control the construction/initialization order of statically-scoped objects. gcc, for example, has an init_priority attribute that can be used to control this, see https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html

unwanted constructor calls before main()

I am working on some multi-thread code with pthreads. When I discovered some memory-leaks (via valgrind), I simply added some
cout << " new [some name of class for me]" << endl;
in part of constructors, because I thought I have removed all of them. This revealed that part of them are launched before main(). I have removed everything from main(), so it looks like:
int main(){
return 0;
}
Even without any #includes those constructors are still invoked. I think nothing from the previous code should be invoked in this case. I used "project clean" option in eclipse and try to delete binaries (Debug/Release). Nothing helps ..
What is the purpose of that? What else I can do?
Thanks in advance.
global and static variables are initialized before main. Except for the static variables declared inside a function. They are initialized on a first call. So I think you should look at the static and global variables

Using init_seg to call an initialization function

I am trying to ensure a function will get called first by the program to ensure the initizilation of critical objects. However, I am confused as to how init_seg is suppose to be getting used/called.
For example, from the documentation at msdn it would seem as if the following would be the first to be called.
#pragma init_seg( ".CRT$XCC" )
static void InitializeStuff()
{
printf("InitializeStuff\n");
}
However, that does not seem to be the case as that function will just plainly not get called automatically (unless I call it explicitly, of course).
How can I use init_set to ensure a function is called before the rest of my other executing code?
If i have understood it right you place all global variables that you want to be initialized first in the same file as the #pragma init_seg
Example:
#pragma init_seg( ".CRT$XCB" )
class A
{
A()
{
printf("first!\n");
}
};
static A first;
And make sure you dont place any other globals in that file than the ones you want to initialized first.

Code breaking when trying to set member variable in constructor

I have a class like this:
class Player
{
public:
Player(Board * someBoard);
void setSide(char newSide);
protected:
Board * board;
char side;
};
and its implementation is as such:
Player::Player(Board * someBoard)
{
board = someBoard;
side = '0';
}
void Player::setSide(char newSide)
{
side = newSide;
}
Now I have another class inheriting from it:
class HumanPlayer : public Player
{
public:
HumanPlayer(Board * someBoard);
};
And its short implementation is this:
HumanPlayer::HumanPlayer(Board * someBoard) : Player(someBoard)
{
}
Now the problem is the side = '0'; line makes the program freeze (the window turns white in Windows 7, not sure if that means it froze or crashed). Commenting it out make the program run fine (and it's okay to comment it out because the variable isn't used anywhere yet).
What is causing the error and how can I fix it?
EDIT!
After printing out some stuff to an fstream, all of a sudden the program worked. I tried commenting the printing out. It still worked. I tried deleting the debugging code I added in. It still worked. So now my code is exactly the same as listed above, but it magically works now.
So what do I do now? Ignore the anomaly? Could it have been a compiler mistake?
I suspect the problem isn't what you think it is.
It sounds like a memory corruption issue of some sort, but it's really impossible to tell based on the information provided. I have two suggestions for you:
Either post the smallest complete program that demonstrates the problem, or
Try a valgrind-type tool to see if it helps you figure out what's going on.
Or, better yet, start by looking at the state of the program in the debugger (once it's hung.)
Is it possible that you are using two incompatible definitions of your Player class, defined in different header files? If the definitions have different sizes, then the 'size' member might lie outside the memory block allocated for the class instance.
Edit I see that your problem has disappeared. So it was probably a module that didn't get re-compiled after a change in the class definition; but now that you've re-compiled everything, the problem has fixed itself.