I'm testing an example about strings in C++ from "C++ Premiere" book.
const int size = 9;
char name1[size];
char name2[size] = "C++owboy"; // 8 characters here
cout << "Howdy! I'm " << name2 << "! What's your name?" << endl;
cin >> name1; // I input "Qwertyuiop" - 11 chars. It is more than the size of name1 array;
// now I do cout
cout << "Well, your name has " << strlen(name1) << " letters"; // "Your name has 11 letters".
cout << " and is stored in an array of " << size(name1) << " bytes"; // ...stored in an array of 9 bytes.
How it can be that 11 chars are stored in an array just for 8 chars + '\0' char? Is it becomes wider on compilation? Or the string is stored somewhere else?
Also, I can't do:
const int size = 9;
char name2[size] = "C++owboy_12345"; // assign 14 characters to 9 chars array
But can do what I've written above:
cin >> name1; // any length string into an array of smaller size
What is the trick here? I use NetBeans and Cygwin g++ compiler.
Writing more entries into an array than the size of the array allows invokes undefined behavior. The computer might store that data anywhere, or not store it at all.
Typically, the data is stored in whatever happens to come next in memory. That might be another variable, an instruction stream, or even a control register for the bomb underneath your chair.
To put it simply: your have coded a buffer-overflow bug. Don't do that.
In one particular case, the behavior increases my bank balance from $10 to $1.8 billion: http://ideone.com/35FQW
Can you see why that program might behave that way?
name1 is given an address in memory. If you write 80 bytes to it, it will write over 80 bytes in memory starting at that location. If there is a variable stored at name1's address + 20, then it will have its data overwritten by your write of 80 bytes to name1. That's just the way things work in C/C++, these are called buffer overflows and can be used to hack programs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With