Home > Software design >  Strange C output with boolean pointer
Strange C output with boolean pointer

Time:05-11

I have the following code:

#include <iostream>
using namespace std;

int main() {
    int n = 2;
    string s = "AB";
    bool* xd = nullptr;
    for (int i = 0; i < n; i  = 100) {
        bool b = (s.substr(0, 2) == "AB");
        if (xd == nullptr) {
            bool tmp = false;
            xd = &tmp;
        }
        cout << "wtf: " << " " << (*xd) << " " << endl;
    }
}

When I run this on my own mac with g -std=c 17, I get a random integer every time (which is odd since *xd should be a bool). Weirdly enough, this doesn't happen on online IDEs like csacademy and onlinegdb.

CodePudding user response:

if (xd == nullptr) {
    bool tmp = false;
    xd = &tmp;
}

tmp is an automatic variable. It is destroyed automatically at the end of the scope where the variable is declared. In this case, the lifetime of the object ends when the if-statement ends. At that point, the pointer xd which pointed to the variable becomes invalid.

(*xd)

Here, you indirect through an invalid pointer. That's something that a program must never do. The behaviour of the program is undefined. The program is broken. Don't do this.

  • Related