Sams Teach Yourself C++ in 21 Days

(singke) #1
LISTING8.9 Creating a Stray Pointer
1: // Listing 8.9 - Demonstrates a stray pointer
2:
3: typedef unsigned short int USHORT;
4: #include <iostream>
5:
6: int main()
7: {
8: USHORT * pInt = new USHORT;
9: *pInt = 10;
10: std::cout << “*pInt: “ << *pInt << std::endl;
11: delete pInt;
12:
13: long * pLong = new long;
14: *pLong = 90000;
15: std::cout << “*pLong: “ << *pLong << std::endl;
16:
17: *pInt = 20; // uh oh, this was deleted!
18:
19: std::cout << “*pInt: “ << *pInt << std::endl;
20: std::cout << “*pLong: “ << *pLong << std::endl;
21: delete pLong;
22: return 0;
23: }

*pInt: 10
*pLong: 90000
*pInt: 20
*pLong: 65556
(Do not try to re-create this output; yours will differ if you are lucky; or your computer
will crash if you are not.)

OUTPUT


246 Day 8


NOTE Stray pointers are often called wild pointers or dangling pointers.

Listing 8.9 illustrates creating a stray pointer.

This program intentionally creates a stray pointer. Do NOT run this
program—it will crash, if you are lucky.

CAUTION
Free download pdf