上QQ阅读APP看书,第一时间看更新
Accessing out of Bounds
When you allocate a buffer, whether on the stack or on the free store, and you get a pointer, there is little to stop you from accessing memory you have not allocated--either before or after the position of the buffer. This means that when you use pointer arithmetic, or indexed access on arrays, that you check carefully that you are not going to access data out of bounds. Sometimes the error may not be immediately obvious:
int arr[] { 1, 2, 3, 4 };
for (int i = 0; i < 4; ++i)
{
arr[i] += arr[i + 1]; // oops, what happens when i == 3?
}
When you use indexing, you have to keep reminding yourself that arrays are indexed from zero so the highest index is the size of the array minus 1.