[ fromfile: ptrpathology.xml id: ptrpathology ]
In Section 1.14, we introduced pointers and demonstrated some of the basics of working with them. We now look at two short code examples to demonstrate some of the weird and dangerous things that can happen when pointers are not handled correctly.
Example 22.1. src/pointers/pathology/pathologydecls1.cpp
Example 22.1 shows a few of the many ways one can declare pointers.
A beginner would be forgiven for thinking the second line of main() creates three pointers - after all, in line one, similar syntax creates three integers.
However, when multiple variables are declared on one line, the * type modifier symbol applies only to the variable that immediately follows it, not the type that precedes it. That is why we recommend having a separate declaration (on a separate line) for each pointer.
Example 22.2. src/pointers/pathology/pathologydecls2.cpp
[ . . . . ]
int main() {
int myint = 5;
int* ptr1 = &myint;
cout << "*ptr1 = " << *ptr1 << endl;
int anotherint = 6;
// *ptr1 = &anotherint;
int* ptr2;
cout << "*ptr2 = " << *ptr2 << endl;
*ptr2 = anotherint;
int yetanotherint = 7;
int* ptr3;
ptr3 = &yetanotherint;
cout << "*ptr3 = " << *ptr3 << endl;
*ptr1 = *ptr2;
cout << "*ptr1 = " << *ptr1 << endl;
return 0;
}
[ . . . . ]
Example 22.2 contains three groups of statements. Only the first and third groups are equivalent; the second contains a common beginner's mistake.
src/pointers/pathology> g++ pathologydecls2.cpp pathologydecls.cpp: In function `int main()': pathologydecls.cpp:17: error: invalid conversion from `int*' to `int' src/pointers/pathology>
After commenting out the invalid conversion, we can try again.
*ptr1 = 5 *ptr2 = 1256764 *ptr3 = 7 *ptr1 = 6
The value of *ptr2 is unpredictable.
Dereferencing uninitialized pointers for read purposes is bad enough, but then we wrote to it.
This is a form of memory corruption, which can cause problems later in the program's execution.
Notice the inconsistent value that *ptr1 obtained from *ptr2.
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |