简体   繁体   中英

C++: Write to/read from invalid/out of bound array index?

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<\/em> 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.

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

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 :)

I think what you need to understand is the following:
when you creating a[4] the compiler allocate memory for 4 integers and remember in a the address of the first one: ( *a == &(a[0]) ).
when you read\\write the compiler doesn't check if you in the bounds (because he doesn't longer have this information). and just go to the address of the requested cell of the array in the following way: a[X] == &(a + sizeof(int) * X)
in C++ it's the programmer responsibility to check the bounds when accessing an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM