0

When I tried the code below, I found there's a problem

Run-Time Check Failure #2 - Stack around the variable 'name' was corrupted

#include <iostream>

using namespace std;

int main() {
    char name[1];
    cout << "Input:";
    cin >> name;
    cout << (int)name << endl;
    system("pause");
    return 0;
}
user438383
  • 5,716
  • 8
  • 28
  • 43
Maxwang
  • 3
  • 1
  • 8
    `char name[1];` is too small. It allows for 1 character of storage. Since even a 1 character string takes two characters there's nothing you can input that won't overflow the array bounds. – Retired Ninja Oct 16 '21 at 06:17
  • @RetiredNinja Now it works! Thanks a lot for your help! – Maxwang Oct 16 '21 at 06:21
  • 4
    Interestingly it looks like C++20 [changed the behavior](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2) for `operator>>` to avoid the UB here. – Nathan Pierson Oct 16 '21 at 06:38
  • 1
    [`using namespace std` is bad](https://stackoverflow.com/q/1452721). – glibg10b Oct 16 '21 at 06:52

0 Answers0