为什么 cin.get(char, int) 不会溢出?



这是我的代码:

#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
const int size = 10;
char test[size];
char test2[size];
cout << "the size of test is " << sizeof(test) << endl;
cout << "input a sentence:" << endl;
cin.getline(test, 50);
cout << "your input is: " << test << endl;
cout << "the size of test is " << sizeof(test) << endl;
cout << "-----stop-----" << endl;
return 0;
}

我在 Clion 中使用MinGw-w64 3.1对其进行了测试,结果如下:

the size of test is 10
input a sentence:
this is a very long sentence
this is a very long sentence
your input is: this is a very long sentence
the size of test is 10
-----stop-----
Process finished with exit code -1073741819 (0xC0000005)

直到我完成所有输出,它才停止。它不应该在我尝试读取数组测试的那一刻停止吗?毕竟,我声称尺码为 10,但试图读取尺码 50。

然后我用gcc 5.4.0在 Ubuntu 下测试了这个,它没有给出任何错误消息!我想知道为什么它没有停止?

因为你(不(幸运!

这是我得到的:

Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
the size of test is 10
input a sentence:
this is a very long sentence
your input is: this is a very long sentence
the size of test is 10
-----stop-----
Abort trap: 6

你目睹的是未定义的行为,这意味着当你的代码执行时会发生什么是未定义的。

最新更新