| C Tutorial | Uninitialized pointers | |||
|
Data types in C
|
When using pointers, there are two entities to keep track of. The pointer and the memory it is pointing to, sometimes called the "pointee". There are three things which must be done for a pointer/pointee relationship to work...
(1) The pointer must be declared and allocated
(2) The pointee must be declared and allocated
(3) The pointer (1) must be initialized so that it points to the pointee (2)
The most common pointer related error of all time is the following: Declare and allocate the pointer (step 1). Forget step 2 and/or 3. Start using the pointer as if it has been setup to point to something. Code with this error frequently compiles fine, but the runtime results are disastrous. Unfortunately the pointer does not point anywhere good unless (2) and (3) are done, so the run time dereference operations on the pointer with * will misuse and trample memory leading to a random crash at some point.
{ int* p;
*p = 13; // NO NO NO p does not point to an int yet // this just overwrites a random area in memory }
Of course your code won't be so trivial, but the bug has the same basic form: declare a pointer, but forget to set it up to point to a particular pointee.
Want To Know more with Video ???
|
|