[ fromfile: ptrpathology.xml id: ptrpathology ]
In Section 1.15, 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 21.1 shows a few of the many ways one can declare pointers.
Example 21.1. src/pointers/pathology/pathologydecls1.cpp
That is why we recommend having a separate declaration (on a separate line) for each pointer.
Example 21.2 contains three groups of statements.
Example 21.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; } [ . . . . ]
This code illustrates some serious pointer issues, the worst of which are not detected by the compiler.
The first is simply a type mismatch.
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 try again.
*ptr1 = 5 *ptr2 = -1218777888 *ptr3 = 7 *ptr1 = 6 Segmentation fault
Dereferencing the uninitialized pointer ptr2
gives unpredictable (i.e., undefined) results.
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.
The Segmentation fault was caused by the memory corruption that occurred when we dereferenced ptr2
.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |