Simple bugs that crashed my mind

This post is more about a memorial of my errors or those I found during the years than a tutorial or research entry. Even though, I'll try to give an explanation about why it happened and what we try to take into account for the future. They're usually simple errors but hard to find when you don't know what you're looking for. Some times it crashes but other times it just causes unexpected behavior.

I've some for C++ and other about Qt. I think it's quite interesting to see both of them because their types and reasons are quite different. While in C++ we have full control about memory allocation and deallocation in Qt we have the re-parenting issue.

Simple bugs in C++

Old C-style arrays are deprecated

The other day I was having some random crash with what look like a corrupted stack, but everything was fine. I had fill an array of doubles in a loop and it was coded in old C-style:

Despite the fact of having the number 12 hard coded, don't you see anything weird? Yes, the parentheses! Array is in fact a pointer to a double with value 12 and then we were iterating over the unknown. Why we don't use the std::array type? It'd be easy, nice and clean:

As you can see: easy, clean and without any problem!

When you mix up pointer to an object with references of an object

This has happened several times because it's not intuitive what we want to achieve. The code compiles and runs properly, almost. I've a structure as a singleton where I take one object, update or modify it and then I commit the changes to the database. I'll show just the part of the code necessary:

First of all, we'll get close to the functionality of the commit method. There we get a clip, modify it and the commit. The clip is modified, and commit properly to the database. The problem is that I was doing a copy of that clip, I was not modifying the clip IN the DataStructure. The solution was easy:

The problem now is: what happens if id is not found? We return a reference of a temporary object, so when we go out of the post method scope it is dereferenced and removed. So our pointer is not valid anymore. Obviuosly if we want the modification and commit behavior we have two options: do it inside the DataStructure or return a pointer or nullptr instead:


A variant of the previous one

In the code above I said I have a method postPtr (int id) that returns a pointer to a Post of the inner map. The reason I have it is to allow other programmers to access that structure and modify the data. If a user wants a specific Post but doesn't want to modify it, I have another method called getPost (int id) const that returns a const reference to a copy of the object with that id and if it's not found it returns a new object so the user can check if is valid.

I say so because today I found a crash in the application because it was supposed to user getPost () instead of the pointer return. Every call inside that particular method was only to get information from the Post instead of modifying the data. In that method it should be used the constant method. But instead, it was used the pointer without checking if it was nullptr.

In addition, the method had two calls to a get method that in addition to return the value it applies an internal operation that modifies it. So:

  1. The reason was crashing is because the method called changed from getPost to post. From const reference of an object to a pointer to an object (or nullptr!)
  2. The reason of that change is because we need to make some modifications in that Post object in that method but the change log only shown that get methods where called.
  3. One get method wasn't a const method as its name indicate. It was doing more than the name of the method

So remember: the name of the method must explain what the method does and the method only must do one thing at a time. If it's a get method it must be const always.

Simple bugs in Qt

Easy to create, easy to copy

One of the main problems of Qt is that we are use to really on copy-on-write (COW) optimization and therefore we assume that we can write atrocities like the following:

I really don't know from where I start, I just so wrong in all ways that the best way is just to remove everything and start from scratch. The variable <em>mSet</em> is a field of the class, as you can see by the allocation is a pointer to a QSet of integers.So, let's start with the first line or better say for the absence of a previous one:

We just had the first line and we cause the first memory leak. After that we call the static method fromVector with a temporary object that is destroyed after using it. The same happens with the temporary object from that method when we pass the parameter to the fromList. So, in a single line we have 3 expensive object creations (temporary QVector, temporary QList and temporary QSet). In this particular case we cannot use std::move since the parameter the static methods are waiting for is a const reference. In the following line we take that temporary object and pass it as a constructor parameter to create a new QSet and it performs a deep-copy. Wonderful!

Please, take into account that most of the times is easy to add a single loop than several calls to static methods chained:

The loop of the death

This particular bug has happened to me several times and the reason is simple: too fast writing code. Remember to double check your call al the time! In the following code I had to process an event, do some operations and then pass to the base class so it can continue its flow:

It was solved before was committed but is so embarrassing I wanted to have it here.

Signals with params between threads

In Qt as well in other frameworks or libraries we have signals that allows us to send parameters using some sort of callback system (we'll see the inner implementation in further post). It means that we can also use it to send information between threads. But we always must remember what are we sending. In the following code I've avoided all the noise of the macros and declarations so we can focus on the signal's parameter:

This is a potential failure. If we are sending constant references to an object between threads is possible that when the signal is processed, the data is no longer valid. We always must send copies of an object or if we want to share data, a shared pointer:

And that's all... for the moment!


Logging with Qt

Logging with Qt

Logging messages is an important part of our app and sometimes we can't find the right way to do so. It depends on how we want to work with that but of course that Qt provide us with some nice options.

Redirect QDebug to a file

Some times we prefer to analyse the our application debug messages in a separated file. It is useful when we want to work with Qt-Creator in full code window and we have two monitors (one for coding and another for application execution and debug file). To redirect the output we have to type in Qt:

Then, in main function we have to add the following line:


Redirect QDebug in our custom class

If we want to redirect the output of our custom class to QDebug, it is necessary to declare the operator << of QDebug type as a friend method:

friend QDebug operator << (QDebug d, const Protocol &p);

Have you own logger

Time ago I created a simple logger, nothing fancy, but easy to integrate. It's a single class that manages several files depending the module and the log level. It makes easier to integrate in your code since there is no dependencies, linking or anything else you need to take into account.

Initially it's planned to be organized by modules, so for each "part" of your code that you want to log it can only be a file. It gives you the possibility to structure your code in different layers and log them. For now, all log messages of a module are printed in the same file, whatever their log level is.

The way to work with this logger is really easy:

The next task I have is to make possible to create files by log level instead of by module. For me it looks a bit messy since you may lose the code traceability, but it's easier to show errors or warnings.


Range-based loop in C++11

Since C++11 we have a new awesome range-based loop. It is an evolution of the always know for-loop but with implicit iterators management. In C++ we can write loops in a different way, for instance the do-while loop, the while loop and the for-loop. In this last case we take an initialization expresion, a condition that must be fulfilled and finally a post-event sentence, almost always used for increment/decrement. When I started coding at the university I couldn't use the STL containers. When I discover Qt I didn't know anything about iterators and I kept iterating for-loops using the size/count method, that was totally aberrant as you may see. Some time ago I learned to work with iterators but with some laziness since I had to write the whole type.

For-loop before range-based loop

I know that I may by a bit basic but I like to show some old and wrong ways to write for loop. I think that sometimes in blogs we forgot that people with more basic knowledge may read this post and I like to give them the basic knowldge too. I've used lists because iterating them is the worst way we can do things. In a future post I'll talk in-depth about containers and performance.

In this case it's clear that we are looking up for a value in the list based in its position. The problem here is that a list is randomly allocated in memory so it's really expensive to look for a value in a position. In addition we're checking the size of a list that is not changing every iteration. We better move to iterators:

This code is almost good. The only problem is that we're using the non-const iterator while we aren't doing anything with the iterator neither the list. The best way would be to change for const_iterator in all sentences:

That's righ but boring to write and tricky to remember that all iterators have to be const_iterator.

Range-based loop

Before C++11 there was no way to make the loops more readable so for that moment it was OK. Now, we have a new syntax we can use in this kind of loop called range-based loop. In addition we have auto keyword that will help us a lot. So instead of that loooooong iterator thing definition we have:

The reason we can work with that is because internally it takes the begin and end iterators and increments the iterator after the body of the loop. It allows us to work with iterators as well as const_iterators, work with object copies, const references or the reference itself. I think it's simple and intuitive.


My C++11 favorite features

Where I came from

I started developing C++ at university where I had my first contact with programming languages. I always had a computer at home since MS-DOS but I never knew or asked myself about how applications run until I started the university. When I started I found it difficult to think as a computer so my efforts where more oriented to memorize routines. Totally wrong, as you may see.

I've always worked with C++ during my university studies but it doesn't mean that I knew how it works or how to use it properly. In fact, the first year I didn't learn OOP at all, it was just structural programming to learn about loops, arrays and basic data structures. The main problem: not a single explanation of why we were using it in that way. Time after that I started with OOP, some templates and finally the conjunction of OOP with GUI applications. A total disaster as you will find out.


Thanks to Qt I discovered several years ago the containers, multithreading, basic algorithms and networking. Signals and slots are Qt particular so I'll talk about them in other posts in the future. Anyway, I still had a problem with C++ basis. About 2 or 3 years ago I discovered that my knowledge in C++ was really limited to 03 version. So I started learning and practising C++11 (in 2015 to say so).

After all this time I've decided to re-take the blog I had for Qt and extend it to C++ with all the experiments and things I've learned. I think it could be useful to anyone who wants to learn new things while it is the same impasse I was before. That's why I've decided to explain in detail my C++11 favorite features. For that purpose I found really useful the book from Scott Meyers.

My C++11 favorite features

The auto specifier

One of my C++11 favorite features is the addition of auto as specifier of data type. It means that we no longer need to write the exact type of data but it is deduced by the compiler. The first thought that came to my mind when I saw it was "Oh shit! C++ has become a Javascript-like language" (I hate untyped languages). But after a while using it I'm converted: it's powerful, it keeps things organized and it avoids errors!

Another case is when we have large data types and we need to write them several times, it makes the code less readable.

The auto word is also useful to avoid automatic cast. Some times we want to just need float precision or even the integer part of number instead of a double. In that case is better to cast it explicitly so another developer will see it easily:

It's also important to be aware of the return type of a method or function. A common mistake is to cast the size of a vector into an integer or even a unsigned int. We must know that the return of size() method of vector is size_type and even it is supposed to be unsigned it doesn't mean that is an unsigned int. In Windows 32-bits both size_type and unsigned int have the same size (32-bits). But in Windows 64-bits size_type is 64-bits long!

Use delete and default keywords

Here there are two different aspects of a common behavior: the method declaration. By using delete what we are telling to the developer is that this method cannot be used or called from anywhere. It is useful for methods that need to be declared but not implemented neither accessible. Let's see an example with class constuctors and imagine we don't want anybody copying our object:

The copy constuctor and the assignment operator are not defined and in theory not visible. Except if you add a friend class to it! In that case we will get a link problem because we do not have the methods defined. But, if we don't want to define them we could use the delete word that does for us:

A similar thing happens with default keyword. In C++11 we have two new special member functions that C++ is willing to generate on its own. In addition to default constructor, copy constructor, destructor and assign operator we have move constructor and move assignment operator (I'll talk more about them in further C++11 favorite features posts). Those last methods will be generated if the following three conditions are true:

  • No copy operations declared
  • No move operations declared
  • No destructor declared

So, imagine the following code:

In this particular case we have a move constructor and move assignment operator defined without we explicitly did. So, if we don't need anything else, or we want not to be generated automatically, we can use default:

In addition, default word tells the compiler to explicitly create the destructor.

Do you use inheritance? Override is your word

When we work with inheritance we find that one of the most common problems is to know if we are using polymorphism or just adding a new method with the same name as the base class. That's a problem when we declare the variable of a type and then we create it in another. Let's see in an example:

In this case the code compiles without any problem. The real issue here is that speed() doesn't return a double because it's not calling the B class method. We declare our object with type A and because of the method is not virtual, the real construction when we allocate memory doesn't matter. The method called will come from the declared type.

When we use override, it tells us in compile time wether the method we want to overload is declared private in the base class. If it's not, the compilation will fail with the error message C3668: "method with override specifier 'override' did not override any base class methods".

In the code above there are two problems solved. The first one is the polymorphism in runtime that is solved by using virtual in the method. The second problem is solved by using override so we avoid any possible undesired behavior if the base class changes in the future.

The scoped enums

One of my C++11 favorite features is the scoped enums. They are simple data types that allow us to use them in the same way than unscoped enums but strongly typed. It means that we can avoid strange behaviors and common mistakes by using the same values from different enums. Let's see some examples:

There are so many things that are not right...

First of all, we are overriding the white color with a different value. It means that if we want to differentiate we must add the scope (Color or FontColor), but we could forget it! Enum class solves it by making mandatory the scope declaration. In addition we are using an enum type for a comparison against an int what is a bit odd. We can still use it in scoped enums, but we have to explicitly cast to it.

Initialize in header file and use nullptr

Here there are several new nice things. All of them are some of my C++11 favorite features, specially the member initialization in header files.
How many times did we forget to initialize class fields that turn on undefined behavior? How many times we did that in the default constructor but then we forget to do it in one of the many override constructors? Now we can initialize all fields in the header file.

IMHO for pointers to objects the best way to initialize them in the header file is just setting them as nullptr. Otherwise we have to include the dependence and it would slow down the compilation time. It would be different if we must include that declaration: in that case we can allocate the memory on it.

It leads us to the use of nullptr instead of NULL or 0. We can still use those values but we should avoid them since nullptr doesn't have an integer type as it happens with the other. For that reason some calls could be different in some scopes:

In the code above, the use of NULL calls the constructor with an int what it may not be what we want. The second constructor will call the right constructor since it has not integer type.

In further posts...

I know that I missed some things in my C++11 favorite features, probably the most important. The reason why I did it is because they're so vast and impacts in so many things that I consider they deserve a specific post for each one. Of course I talking about the use of braces ({}) when creating objects, smart pointers and rvalue references (move semantics and forwarding references). Another reason I choose to explain them in another post is because the extension of this first one would be so huge that nobody would read it. In addition, the smart pointers feature has a similar extension in Qt that I'd like to talk about too.

Finally, another future topic will be the loop management and in Qt and C++. There are several post in the internet and I'd like to put them together in one place. So for the moment these have been my c++11 favorite features!