0

I am using mingw compiler on my windows 10 laptop. The following c code should display a segmentation fault error. But instead, it just does not show anything (empty output).

#include <stdio.h>

int main(){
    main();

    return 0;
}

I compile the code using:

gcc filename.c

But when I use some online c compilers, it shows segmentation fault. Please tell me how to get segfault error. It is hard to debug the large code if I don't get any error.

Related: How to get back plain old "Segmentation fault" message in windows?

yogeshwar
  • 591
  • 4
  • 5

1 Answers1

1

Let's see the assembly: -O0: (No optimizations,gcc, just a bit stripped):

main:
    pushq   %rbp #Push address to stack
    movq    %rsp, %rbp
    movl    $0, %eax
    call    main
    movl    $0, %eax
    popq    %rbp
    ret

You just call a function recursively, always pushing the return address to the stack. But after some implementation/platform defined number of calls there is another memory. You just overwrite it or you access invalid memory. (Segmentation fault)

You can see it like this:

High=======Lower addresses

[stack].....[someOtherMemory]

...recursive call...

[stack  ]...[someOtherMemory]

...recursive call...

[stack    ].[someOtherMemory]

...recursive call...

[stack      ]someOtherMemory]

Kaboom: You accessed the other memory, that was maybe not writable/readable => Crash

Now, you can compile with higher optimizations: -O3, example output, stripped again:

main:
    jmp main

It is just an infinite loop. Theoretically both would have the same result. The compiler is nearly allowed to do anything, as long as the observable output stays the same (See: https://stackoverflow.com/a/46455917/13912132).

But in the first, it is translated "literally", leading to hitting other parts. But if no other parts would be hit, it would run all the time.

In the second, the compiler may see, that this would run infinite theoretically, so it got optimized.

JCWasmx86
  • 3,473
  • 2
  • 11
  • 29
  • I just wanted to know if my program terminates abruptly without giving an output, how shall I realize that it is segmentation fault? Segfault is pretty clear in recursive calls but what if the code is more complex? – yogeshwar Apr 30 '21 at 19:28
  • The debugger shows it. It's shown on the console, a signal called SIGSEGV is "thrown", the exit code may indicate a segmentation fault – JCWasmx86 Apr 30 '21 at 19:39