1

I'm facing a strange behaviour in my windows 10 development environment.

I compile the following code (mingv gcc-8.1.0)

int main(){
    char* x = nullptr;
    std::cout<<*x<<std::endl;
    return 0;
}

When I run this program in a cmd or powershell window, it outputs a blank line, waits for a bunch of seconds and then returns to prompt.

I'd love to have it print "segmentation fault" and exit immediately, as god intended.

If I run the program in GDB the error is shown correctly (Thread 1 received signal SIGSEGV, Segmentation fault.).

Could someone please explain why it does this and if there is a way to obtain the desired behaviour?

Related: Why won't my code segfault on Windows 7?

vvigilante
  • 113
  • 1
  • 9
  • 1
    *I'd love to have it print "segmentation fault" and exit immediately, as god intended.* Welcome to undefined behavior land, the place god forgot about. – NathanOliver Apr 13 '21 at 14:52
  • There are some nasal demons though. – Eugene Sh. Apr 13 '21 at 14:57
  • Why the C tag? This is not C. – klutt Apr 13 '21 at 15:00
  • 1
    @klutt The example code is C++, but the problem is not C++ specific. I removed both C and C++ tags. – vvigilante Apr 13 '21 at 15:05
  • If you want a `SIGSEGV`, there's `raise(SIGSEGV)`. If you want to print "Segmentation fault.", try `std::cerr << "Segmentation fault.\n";`. If you want Linux, you can even find it in the Windows Store these days. – MSalters Apr 13 '21 at 15:10
  • 1
    It is not, in general, reasonable to rely on null pointer dereferences in C or C++ to produce any specific behavior, including segfaults. This is the meaning of the "undefined" in "undefined behavior". – John Bollinger Apr 13 '21 at 15:11
  • 2
    @JohnBollinger thank you for your answer. I understand, but in this specific case the compiler is generating the illegal access as expected, as we can see through the debugger; nasal daemons are not there: the segfault IS generated, just not displayed. My question is more about "why is the error hidden when I do not use a debugger? Can I change that? How? What is happening in those seconds before the prompt comes back?". – vvigilante Apr 13 '21 at 15:20

0 Answers0