【发布时间】:2013-12-02 17:47:19
【问题描述】:
我的代码是
char buffer[10]={0};
cin>>buffer; //here i enter the contents as "12345678912345"
//Now i tried to enter 14 characters into a buffer of 10
cin>>buffer; //This works as it waits for input on the console
cout<<buffer;
而
char buffer[10]={0};
cin>>buffer;//same input as above "12345678912345"
cin.getline(buffer,10);//This doesn't wait for input on console and returns
cout<<buffer;
为什么会这样?
感谢: 感谢大家的回答,他们很有帮助
【问题讨论】:
-
您是否在问为什么在缓冲区溢出后会出现未定义的行为?那是因为缓冲区溢出会导致未定义的行为。
-
但如果是 cin>> 它工作正常
-
不,它没有;它写入超过缓冲区的末尾,破坏内存并导致未定义的行为。如果损坏的内存中碰巧没有什么重要的东西,它似乎对你有用;但原则上任何事情都可能发生。