为什么cin改变了我的引用变量的地址?

我正在学习 C++ 并为自己创建了一些实验案例来了解引用和指针。我遇到了将引用变量传递给函数的情况,但是当我尝试在函数内更改其值时,值更改并未在函数外持续存在。我花了很长时间来缩小正在发生的事情的范围,结果发现该函数cin.ignore()正在更改我的变量的地址。

测试代码:

int main() {
    bool mainBool = false;
    printf("Address of mainBool: %pn", &mainBool);
    while (!mainBool) {
        boolTest(mainBool);
    }
    return 0;
}

void boolTest(bool & var) {
    printf("Address of bool passed in: %pn", &var);
    printf("> ");
    char input[2];
    std::cin >> input;
    std::cin.ignore();
    printf("Address of bool after cin.ignore(): %pn", &var);
    var = true;
    return;
}

输出:

Address of mainBool: 0x7ffeefbff4bb
Address of bool passed in: 0x7ffeefbff4bb
> 00
Address of bool after cin.ignore(): 0x7ffeefbff400
Address of bool passed in: 0x7ffeefbff4bb
>

使用“00”作为我的用户输入,main() 函数将永远循环。

我认识到我cin.ignore()在这种情况下的使用没有正确设置以适应不正确的输入长度。但我不明白为什么这会在这个范围内改变我的变量的地址。任何人都可以解释或指出一些可能解释幕后发生的事情的资源吗?

回答

在我看来,您遇到了缓冲区溢出,因此出现了未定义的行为。问题是char input[2];只能容纳两个字符而不能容纳更多字符。不幸的是,您的输入"00"需要三个字符才能存储为 C 字符串 - 您不能忘记空终止符!

  • *you can't forget the null terminator!* Wish this was literally true. Save a lot of bugs.

以上是为什么cin改变了我的引用变量的地址?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>