Why stack overflow causes segmentation fault instead of stack overflow in Linux?

RajSanpui picture RajSanpui · Aug 8, 2011 · Viewed 13.1k times · Source

Possible Duplicate:
What is the difference between a segmentation fault and a stack overflow?

I was just wondering, why stack overflow results in segmentation fault instead of stack overflow.

Is it because the boundary of stack limit is crossed which causes SIGSEGV? Why we don't encounter stack overflow in Linux, and rather a segmentation fault?

int foo()
{
  return foo();
}

This small code should cause stack overflow but rather it causes segmentation fault in Linux.

Answer

ninjalj picture ninjalj · Aug 8, 2011

A stack overflow can cause several different kinds of hardware errors.

  • It may lead to an attempt to access memory for which the program has no appropriate permissions → the kernel will raise a SIGSEGV (segmentation violation) signal for the process.
  • It may lead to an attempt to execute an illegal instruction (e.g: you overwrote the return address to point to an invalid instruction) → the kernel will raise a SIGILL (illegal instruction) signal.
  • Probably SIGBUS on some platforms (e.g: alignment exception).

All these errors occur after the stack overflow. An option is to add stack overflow protections (ProPolice, ...), so as to catch stack overflows before they cause more serious problems.

Edit:

You mean a "real stack overflow". Well, this case is covered by SEGV (trying to access memory for which the process has no permissions), so it gets a SEGV, instead of special-casing every single case of the more general SEGV.