0

In GCC, MVSC, Clang, and AppleClang, the code below will compile and always print "no". But when dereferencing the int*, are we actually reading 3 extra bytes into the test variable, and thus it could happen that the code prints "yes" if some of the 3 extra bytes are not 0?

Example Code:

#include <cstdio>

void* fun()
{
    static bool value = false;
    return &value;
}

int main(int, char**)
{
    int test = *static_cast<int*>(fun());

    if (test == 0)
    {
        printf("no");
    }
    else
    {
        printf("yes");
    }

    return 0;
}
James Takarashy
  • 299
  • 2
  • 14
  • 2
    This is undefined behavior. Therefore it means that anything can happen. – Sam Varshavchik Jun 27 '21 at 16:35
  • It might print "no", it might print "yes", it might crash, it might format your hard drive, it might send your browser history to your grandmother, it might awaken Cthulhu from his slumber in the sunken city of R'lyeh, or even worse... it might appear to work. (It crashes on my machine.) – Eljay Jun 27 '21 at 16:50
  • *will compile and always print "no"* [no it will not](https://godbolt.org/z/EEbv53GPe) – n. m. could be an AI Jun 27 '21 at 18:15
  • In your function, you are converting a pointer to `bool` to a pointer to `void`, which looses all type information. There are processors out there that can have pointers to single bits. Casting a single bit to a whole bunch of bits (integer) is undefined behavior. – Thomas Matthews Jun 27 '21 at 18:20
  • In a simple example, a pointer to a `bool` could be implemented as a pointer to a `uint_8` (8 bits, unsigned). Casting the pointer to an integer (32-bits) assumes there are 3 more `uint8_t` memory slots following the one pointed to by the 32-bit pointer. This may not be so (think of the `uint8_t` pointer pointing to the last `uint8_t` in memory). – Thomas Matthews Jun 27 '21 at 18:23
  • Somewhat related question : https://stackoverflow.com/questions/54120862/does-the-c-standard-allow-for-an-uninitialized-bool-to-crash-a-program – François Andrieux Jun 27 '21 at 20:49

0 Answers0