Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stack overflow causes segmentation fault instead of stack overflow in Linux? [duplicate]

Tags:

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.

like image 391
RajSanpui Avatar asked Aug 08 '11 17:08

RajSanpui


2 Answers

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.

like image 134
ninjalj Avatar answered Sep 19 '22 18:09

ninjalj


Stackoverflow is not an error, it is a case, the error thrown from it changes from language to language and from platform to platform.

See more about segmentation fault in wiki

EDIT:

To make it clearer - in your case, the call stack is overflowed and the program tries to write the next call to an invalid address, causing a segmentation fault.

like image 25
MByD Avatar answered Sep 21 '22 18:09

MByD