‘Why you should never use the bool datatype’ — I disagree

Andrey Karpov
2 min readFeb 4, 2020

Today I’ve come across, in my view, a ridiculous article ‘Why you should never use the bool datatype’. I don’t agree with the bool type thing the author says. It’s just a type — there’s nothing bad about it. Moreover, bool is safer than, let’s say, char. Let’s remember a proverbial vulnerability.

The description of CVE-2012–2122: sql/password.c in Oracle MySQL 5.1.x before 5.1.63, 5.5.x before 5.5.24, and 5.6.x before 5.6.6, and MariaDB 5.1.x before 5.1.62, 5.2.x before 5.2.12, 5.3.x before 5.3.6, and 5.5.x before 5.5.23, when running in certain environments with certain implementations of the memcmp function, allows remote attackers to bypass authentication by repeatedly authenticating with the same incorrect password, which eventually causes a token comparison to succeed due to an improperly-checked return value.

Here is the code, having a vulnerability:

typedef char my_bool;my_boolcheck_scramble(const char *scramble_arg, const char *message,
const uint8 *hash_stage2)
{ return memcmp(hash_stage2, hash_stage2_reassured, SHA1_HASH_SIZE);}

The type of the return value of the memcmp function is int, and the type of the return value of the check_scramble is my_bool, but actually — char. As a result, there is implicit conversion of int to char, during which the significant bits are lost. This resulted in the fact that in 1 out of 256 cases, it was possible to login with any password, knowing the user’s name. In view of the fact that 300 attempts of connection took less than a second, this protection is as good as no protection. You may find more details about this vulnerability via the links listed on the following page CVE-2012–2122.

If the bool was used in the following way:

typedef bool my_bool;

Everything would have been right. An int zero would have turned into false and any other value into true.

Example: https://godbolt.org/z/unM7zz

Now let’s talk about alignment and structures’ size. The problem is not worth a damn. If few objects are created then there’s no point in saving memory space and one can simply write ‘bool’ whenever they want in the structure.

Just in case, non-optimal structures can always be detected by the PVS-Studio analyzer. It has a corresponding micro optimization diagnostic: V802. On 32-bit/64-bit platform, structure size can be reduced from N to K bytes by rearranging the fields according to their sizes in decreasing order.

If you really need to be thorough about saving memory space, it’s better to use bit fields in structures instead of bool. Besides, bit fields are better to use compared to power-of-two constants as the author of the article suggests. Bit fields code is simpler and less vulnerable to bugs.

--

--

Andrey Karpov

Founder and DevRel of PVS-Studio static code analyzer for C, C++, C# and Java.