[Solved] C++ input string crash [closed]


char code[1]; Arrays are treated like pointers (they “decay”) when passed to functions. More on Arrays decaying here: What is array decaying?

cin>>code; >>is actually a function, so code is seen as a pointer to char. It treats a pointer to char as though it is a c-style string and attempts to null terminate it. Sadly there is only room for one character and no room for the null terminator, so the null terminator is written to memory that is not owned by the program.

If the program survives that, "You entered the item code : "<<code<<endl. << also treats a pointer to char as though it is a c-style string and attempts to write until it finds the null terminator, reading past the end of the array and from invalid memory and who knows where it will finally find a null character and stop.

Solution:

If you only want one char, define code to be only one char with

char code;

solved C++ input string crash [closed]