Is this an address?

1
2
3
4
5
6
7
8
int main()
{
    int *ptr;
    std::cout << ptr << std::endl;


    return 0;
}


I know that uninitialized pointers should be avoided because they point to some random place in memory. In the example below and using C:B, I got an output of 0x10
what is that 0x10? is it an address or what?
> what is that 0x10? is it an address or what?
Yes, it's the random place in memory that you just said in your previous sentence.

I say 'memory', but it's not likely there is any memory at all at that address. At least not that the OS will allow your program to access.

*ptr = 42; is just going to cause the machine to generate an address error and the OS to kill your program.

If by some random chance ptr happens to point to some valid address in your program's address space, then *ptr = 42; is just like planting a landmine. Sooner or later, your program will try to use that corrupted data and crash in spectacular and unexplainable ways. This is what makes uninitialised pointers so nasty to debug.
if nothing was injected into your code (for example, when debug compiled, most compilers "inject" statements that you did not write to zero or codify variables to a pattern (like 0xCCCCCCC or whatever) then think of it like this:

some program runs on your computer and sets a piece of memory to the value, say its 10. maybe its the number of times it found the letter e in your wheel of fortune game. Maybe its how many furlongs per fortnight were averaged by paul revere. Whatever it was, that program closed some time ago.

now your program starts and the OS sees that this memory location is not in use, so it gives it to your program. You fire up an uninit variable, and the 'random' value it has is simply what the value was last time it was in use. A pointer is really just an integer**, but cout is wired to put it out in hex because pointers have to be displayed in hex as was decreed from on high when moses built the first computer. And so, its 10.

(sorry, 0x10 is really 16, but whatever. 10 is 0x0A, of course .. details).


** if it helps, think of memory as a giant array of unsigned characters. A pointer is, then, the integer array index.
so int *x = new int; //the value of x is conceptually the offset if it were an array: ram[x]

Technically it's undefined behaviour.

jonnin wrote:
now your program starts and the OS sees that this memory location is not in use, so it gives it to your program.

Modern operating systems normally zeroes the memory before handing it to another program for safety reasons.

The reason you see "random" non-zero values when trying to read from uninitialized variables is because your own program has already written to those memory locations before, after it was handed to your program by the operating system.
Last edited on
Topic archived. No new replies allowed.