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?
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With