Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where C++ really stores a string if the char array that stores it is smaller than a string is?

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.

like image 730
Green Avatar asked Nov 29 '22 14:11

Green


2 Answers

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.


Just for fun: Undefined behavior is behavior that the C++ standard does not comment on. It can be anything, since the standard places no constraints on it.

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?

like image 131
Robᵩ Avatar answered Feb 17 '23 03:02

Robᵩ


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.

like image 43
Rocky Pulley Avatar answered Feb 17 '23 04:02

Rocky Pulley