FT TEH FT TEH - 2 months ago 10
C++ Question

C++ input string crash

I am new to C++ and still learning it.I did an exercise on book and everything seems right in my program,but it will just crash when showing the inputs that I entered.I tried to ran it on different compilers and computers,the results were the same.Hope someone will help me thank you.And here is the program.

#include<iostream>
using namespace std;

int main()
{

string name;
char code[1];
float price;
int quantity;

cout<<"Enter an item name : "<<endl;
getline(cin,name);

cout<<"Enter the item code : "<<endl;
cin>>code;

cout<<"Enter the price per unit : "<<endl;
cin>>price;

cout<<"Enter the quanlity : "<<endl;
cin>>quantity;


cout<<"You entered the item name : "<<name<<endl
<<"You entered the item code : "<<code<<endl
<<"You entered the item price : "<<"RM"<<price<<endl
<<"You entered the item quantity: "<<quantity<<" unit"<<endl
<<"The total cost : "<<"RM"<<(quantity*price)<<endl;
return 0;
}


and this is the output:http://i.stack.imgur.com/jpE9N.png

Answer

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;