Coming from Visual Studio/MSVC, I'm expecting that accessing an uninitialized pointer will result in an Access Violation/segfault for Debug builds at least.
This is because Visual Studio fills all uninitialized memory with magic numbers like 0xcdcdcdcd
and the like, and it has protected 0xcdcdcdcd
so attempting to read/write from it will generate an Access Violation.
But to my surprise, GCC on Linux does no such thing, so accessing uninitialized pointers can cause memory corruption even in Debug builds, which can be very hard to debug.
This test code will happily access the memory location in my test app when compiled using GCC:
int *p;
int n = *p;
I am using Qt Creator as my IDE, and I'm compiling a Debug build:
gcc -c -pipe -g -Wall -W -fPIE -I../untitled19 -I. -I/opt/Qt/5.4/gcc/mkspecs/linux-g++ -o main.o ../untitled19/main.c g++ -Wl,-rpath,/opt/Qt/5.4/gcc -o untitled19 main.o
Why does GCC lack such an important feature by default, and hopefully, is there a compiler flag that would enable it?
I've found Magic numbers when debugging with gcc/g++/gdb/valgrind?, but the answers there are very unsatisfactory and basically suggest that you should write your own new/delete implementations, which doesn't even cover uninitialized pointers that are local variables.