[ 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
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 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; } [ . . . . ]
<include src="src/pointers/pathology/pathologydecls2.cpp" href="src/pointers/pathology/pathologydecls2.cpp" mode="cpp" id="pathologydecls2cpp"/>
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
.
The Segmentation fault is not the worst thing that could happen. At least it warns the programmer that there is a serious problem. A worse thing would be if the program did not abort but, instead, ran and produced wrong, but feasible, results. Not many people take the time and trouble to check the computer's arithmetic! With corrupted memory, anything can happen and, because the results are undefined, you can't even rely on the program aborting.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |