Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stack overflow on some machines, but segmentation fault on another?

Just out of curiosity, I'm trying to generate a stack overflow. This code generates a Stack Overflow according to the OP, but when I run it on my machine, it generates a segmentation fault:

#include <iostream>  using namespace std;  int num = 11; unsigned long long int number = 22;  int  Divisor() {     int result;     result = number%num;      if (result == 0 && num < 21)     {         num+1;         Divisor();          if (num == 20 && result == 0)         {             return number;         }     }      else if (result != 0)     {         number++;         Divisor();     } }  int main () {     Divisor();     cout << endl << endl;     system ("PAUSE");     return 0; } 

Also, according to this post, some examples there should also do the same. Why is it I get segmentation faults instead?

like image 632
Alexander Kleinhans Avatar asked May 20 '15 09:05

Alexander Kleinhans


People also ask

Can stack overflow cause segmentation fault?

The function foo, when it is invoked, continues to invoke itself, allocating additional space on the stack each time, until the stack overflows resulting in a segmentation fault.

Why do I keep getting segmentation fault?

In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).

Does buffer overflow cause segmentation fault?

A buffer overflow doesn't necessarily cause a segfault - that's the problem! A guaranteed segfault would be a completely valid and safe way to handle a buffer overflow. But segfaults only happen when your program tries to access memory it does not own.


1 Answers

Why is it I get segmentation faults instead?

The segmentation fault, what you're seeing, is a side-effect of the stack overflow. The reason is stack overflow, the result is segmentation fault.

From the wikipedia article for "stack overflow" (emphasis mine)

.... When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, typically resulting in a program crash.

like image 114
Sourav Ghosh Avatar answered Oct 08 '22 17:10

Sourav Ghosh