Quantcast
Channel: Does the C++ standard allow for an uninitialized bool to crash a program? - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by Steve Summit for Does the C++ standard allow for an uninitialized bool to crash a program?

$
0
0

Does the C++ standard allow a compiler to assume a bool can only have an internal numerical representation of '0' or '1' and use it in such a way?

Yes indeed, and in case it's useful to anyone, here's another real-world example.

I once spent several weeks tracking down an obscure bug in a large codebase. There were several aspects that made it challenging, but the root cause was an uninitialized boolean member of a class variable.

There was a test with a complicated expression involving this member variable:

if(COMPLICATED_EXPRESSION_INVOLVING(class->member)) {    ...}

I began to suspect that this test was not evaluating "true" when it should. I don't remember whether it was not convenient to run things under a debugger, or if I didn't trust the debugger, or what, but I went for the brute-force technique of augmenting the code with some debugging printouts:

printf("%s\n", COMPLICATED_EXPRESSION_INVOLVING(class->member) ? "yes" : "no");if(COMPLICATED_EXPRESSION_INVOLVING(class->member)) {    printf("doing the thing\n");    ...}

Imagine my surprise when the code printed "no" followed by "doing the thing".

Inspecting the assembly code revealed that sometimes, the compiler (which was gcc) was testing the boolean member by comparing it to 0, but other times, it was using a test-least-significant-bit instruction. When things failed, the uninitialized boolean variable happened to contain the value 2. So, in machine language, the test equivalent to

if(class->member != 0)

succeeded, but the test equivalent to

if(class->member % 2 != 0)

failed. The boolean variable was literally true and false at the same time! And if that's not undefined behavior, I don't know what is!


Viewing all articles
Browse latest Browse all 7

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>