Where does uninitialized pointer point to?

1
2
3
4
5
int main()
{
    int* ptr;
    *ptr = 56;
}


This compiles without warning. I thought the pointer had to be initialized before anything could happen. Is this undefined behavior? How can I know whether some behavior is undefined or not? (I tried looking up in library reference but it's hard to navigate..)
Last edited on
When you create a pointer like this, the memory for that pointer is allocated but the contents of that memory are not touched. As such, the value of the pointer, which is just a number representing some other place in memory, is whatever value happens by chance to be in that memory.

It could be pointing anywhere, and the compiler will happily let you use it without initialising it. Some compilers will warn you about it.

When you actually run the program, you will be accessing some random piece of memory; if you're lucky, you'll get a segfault. If you're unlucky, you'll trash data without even knowing it.
Last edited on
Topic archived. No new replies allowed.