In C++ I'm not able to copy a string to another string using for loop. Why can't we copy this way in C++? [duplicate]

First of all, I am a beginner when it comes to C++ programming. Yesterday I encountered something rather strange. I was trying to determine the length of an array via a pointer pointing towards it. Since sizeof didn't work I did a little Google search and ended up on this website where I found the answer that it was not possible. Instead I should put an out of bound value at the last index of the array and increment a counter until this index is reached. Because I didn't want to overwrite the information that was contained at the last index, I tried putting the out of bound value one index after the last one. I expected it to fail, but for some reason it didn't.

I thought that I made a mistake somewhere else and that the array was longer then I assigned it to be, so I made the following test:

int a[4];
a[20] = 42;
std::cout << a[20];

The output is 42 without any errors. Why does this work? This should not be valid at all, right? What's even more interesting is the fact that this works with any primitive type array. However, once I use a std::string the program instantly exists with 1.

Any ideas?


Solution 1:

Your system just happens to not be using the memory that just happens to be 20 * sizeof(int) bytes further from the address of your array. (From the beginning of it.) Or the memory belongs to your process and therefore you can mess with it and either break something for yourself or just by lucky coincidence break nothing.

Bottom line, don't do that :)