C++ Memory Management
My earlier use of the word tramples is important. In that example, the runtime environment is not checking to make sure that the application stays within its bounds. Rather, the runtime environment simply doesn't react until something happens from which it can't recover. This difference may seem subtle—but it isn't. To illustrate this point, take a look at the C++ code in Listing 2.
Listing 2Making an assignment out of bounds.
// Pointers01.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int myArray [] = {2, 15, 24, 36, 48}; int main () { printf("myArray[2]= %d\n", myArray[2]); myArray[33] = 33; printf("myArray[33]= %d\n", myArray[33]); system("pause"); return 0; }
The interesting line of code is this one:
myArray[33] = 33;
Java and .NET programmers might wince—their runtime would certainly pay attention. Obviously the array (myArray) contains only five elements (see Figure 3).
Figure 3 Array memory locations.
How can you assign something to element 33 when that element doesn't exist? In fact, this application actually executes. For proof, look at Figure 4.
Figure 4 Accessing memory location.
Even though element 33 of myArray doesn't exist within array, the C++ application behaves as if it does. In fact, Figure 4 showed that the value of 33 is actually assigned to the supposed location. It's very important to understand that in this case the application didn't crash—even though it literally wrote a value (33) into a location that was not part of its scope.
C++ is a very powerful programming language and can be very forgiving. However, as one of my supervisors once told me, "If you're not very careful, C++ provides just enough rope to hang yourself."