2017-08-05 41 views
1

这是我的代码:为什么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; 

} 

的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.

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

回答

1

因为你是(非)幸运!

这里是我的了:

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 

你所看到的是不确定的行为,这意味着它的不确定你的代码执行时会happenn什么。

+1

看起来你是对的......我用别人的电脑再次测试过,结果不一样。有些出错了,有些出错了......但是它在所有的Windows环境下都会停下来。 – JiangFeng