Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Pointers 247

8


This is a listing you should avoid running because it could lock up your machine.
On line 8,pIntis declared to be a pointer to USHORT, and is pointed to newly
allocated memory. On line 9, the value 10 is put into that memory allocated for pInt.
The value pointed to is then printed on line 10. After the value is printed,deleteis
called on the pointer. After line 11 executes,pIntis a stray, or dangling, pointer.
Line 13 declares a new pointer,pLong, which is pointed at the memory allocated by new.
On line 14, the value 90000 is assigned to pLong, and on line 15, this value prints.
It is on line 17 that the troubles begin. On line 17, the value 20 is assigned to the mem-
ory that pIntpoints to, but pIntno longer points anywhere that is valid. The memory
that pIntpoints to was freed by the call to deleteon line 11. Assigning a value to that
memory is certain disaster.
On line 19, the value at pIntis printed. Sure enough, it is 20. Line 20 prints the value at
pLong; it has suddenly been changed to 65556. Two questions arise:


  1. How could pLong’s value change, given that pLongwasn’t touched?
    2. Where did the 20 go when pIntwas used on line 17?
    As you might guess, these are related questions. When a value was placed at pInton line
    17, the compiler happily placed the value 20 at the memory location that pIntpreviously
    pointed to. However, because that memory was freed on line 11, the compiler was free to
    reassign it. When pLongwas created on line 13, it was given pInt’s old memory loca-
    tion. (On some computers, this might not happen, depending on where in memory these
    values are stored.) When the value 20 was assigned to the location that pIntpreviously
    pointed to, it wrote over the value pointed to by pLong. This is called ”stomping on a
    pointer.” It is often the unfortunate outcome of using a stray pointer.
    This is a particularly nasty bug because the value that changed wasn’t associated with the
    stray pointer. The change to the value at pLongwas a side effect of the misuse of pInt. In
    a large program, this would be very difficult to track down.


ANALYSIS


Just for Fun
Here are the details of how 65,556 got into the memory address of pLongin Listing 8.9:


  1. pIntwas pointed at a particular memory location, and the value 10 was assigned.

  2. deletewas called on pInt, which told the compiler that it could put something else
    at that location. Then, pLongwas assigned the same memory location.

  3. The value 90000 was assigned to *pLong. The particular computer used in this exam-
    ple stored the four-byte value of 90,000 (00 01 5F 90) in byte-swapped order.
    Therefore, it was stored as 5F 90 00 01.

Free download pdf