Uninitialized Pointers in g++ vs MS c++

Viewed 85

Recently, I read a coding example that explained the following would cause a compiler error in Visual Studio:

int* pointer1;
*pointer1 = 10;

The author claimed that since pointer1 is uninitialized before being dereferenced, the following error occurs in Visual Studio:

C4700: uninitialized local variable "pointer1" used

And it does. This scenario makes sense.

However, if I use the exact same code and compile with g++, no compiler error occurs and I'm free to use pointer1 in any normal fashion.

Why the difference? Is g++ assigning an address to pointer1 before initialization?

1 Answers

Try to pass -Wuninitialized -Werror to gcc. Additionally -Wmaybe-uninitialized may help identifying execution paths which leave the variable uninitialized.

On a side note: dereferencing uninitialized pointer is undefined behavior. This means compiler may but does not have to diagnose it. The full blame is on developer.

Related