Writing Past the End of an Array

When you write a value to an element in an array, the compiler computes where to store the value based on the size of each element and the subscript. Suppose that you ask to write over the value at LongArray[5], which is the sixth element. The compiler multiplies the offset—5—by the size of each element—in this case, 4. It then moves that many bytes—20—from the beginning of the array and writes the new value at that location.

If you ask to write at LongArray[50], the compiler ignores the fact that there is no such element. It computes how far past the first element it should be—200 bytes—and then writes over whatever is at that location. This can be virtually any data, and writing your new value there might have ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.