This is just a tiny snippet which ties into my last post about compiler warnings.
Frequently when I'm building a class, I'll stub out a lot of the functions just to get an idea of how things will work. "Stubbing" simply means adding the function declaration/definitions, but instead of having the function actually perform it's task, it's usually either left blank, or does a print statement to show where the control is currently at. That's all fine and well...until you do something like I did.
In order to complete my stubbing, I went as far as to assign one of my class data members, an std::vector<>, to the return of the function that would be used to populate this vector. The problem? While stubbing that said function, I forgot to add a return value! This, coupled with lack of any compiler warning flags, caused a segfault when I ran some testing code.
Now, to the heart of the matter: Why was this so hard for me to track down, aside from improper (absent) warning flags? I was doing my debug print statements with std::cout. The problem? std::cout is buffered, which means things get printed when the OS decides they get printed, not exactly when you tell it to print. After I tried to initialize my vector from the function (of which returned nothing), I made a call to some other class functions, and due to the buffering of my debug statements, it seemed the segfault happened AFTER that other class function returned, but BEFORE control was given back to the constructor that called it. This clearly made no sense, and all of the code looked fine.
Using std::cerr is the optimal choice for debugging output because it gets printed exactly when you tell it to. More importantly, a simple -Wall flag to g++ would have informed me right away that: "control reaches end of non-void function" and immediately I'd know why my program was segfaulting.
So, lessons learned?
1. Enable. Compiler. Warnings.
2. Use std::cerr for debugging output
3. Complete your stubbed functions with return values and proper parameters
Note: I've been told that using std::endl will force std::cout to be printed, but for whatever reason that just wasn't happening for me. *shrug*