Sorry, I screwed the tags up on the previous. This should be easier to read.
Code:
int *iptr; /* these are non-initialized pointer
float *fptr; /* variables and I guess non-legal*/
printf("address of iptr is: %p ", iptr);
printf("address of fptr is: %p", fptr);
The question is: Just where _exactly_ does 'iptr' and 'fptr' point to? Make sure you are not confusing the address of where the variable resides in memory with the contents of the pointer.
'iptr' sits at a specific location in RAM, decided by relative positioning by your compiler and resolved at execution by your link loader.
For example, let's say that 'iptr' and 'fptr' reside _at_ consecutive memory locations:
Code:
Address RAM
------------------------------------------------------------
0x004A72E1 FF 03 FF F8 A5 71 24 EE
0x004A72E9 F1 23 A7 EE 64 51 29 20
...
In the above case, 'iptr' is located at 0x004A72E1. This is the value of iptr (it's ADDRESS) aka where it lives in RAM. If I go indirectly through that address = 'a = *iptr', where 'a' is an int, it will make the contents of a equal to 'FF 03'. This is a negative number.
So when the program starts up, if you have not _initialized_ your variable 'iptr' and 'fptr' to something else (like zero), it will contain whatever value happens to be in RAM at the time.
RAM is not all zeroes.
If program 'A' quits and then your program 'B' executes and is thereby loaded into the memory that program 'A' was previously in, the O/S and the memory manager DON'T clean RAM up. Why would they? It's up to you to zero and clean and maintain space you intend to use.
So, if program 'A' left the Value 0xFF03 at location 0x004A72E1, and your program happens to have variable 'iptr' loaded at that address, its value is going to be 0xFF03 until _you_ specifically set it to something else.
That is _specifically_ why I initialize every pointer I create to zero (NULL) prior to its use. When I deallocate dynamic allocations, I reset their pointers to zero. That way, I can always tell if I'm using a valid pointer by check it against a known state.
Everytime I go to use a pointer, the first thing I do is check to see if it's valid.
Code:
...
if(!myPtr) /* ptr has been allocated? */
return(errCODE); /* nope, bail */
...
If it's non-zero, I have a very good bet that it's a valid pointer. The only other possibility is that some poorly behaved program has rampaged through my RAM and corruped a nil pointer such that it contains something other than NULL.