2

I'm wondering how to get an stack overflow error with a simple example, such as:

int recursSum (int n)
{
   return (n==1)? 1:n+recursSum(n-1);
}

I ask that stupid question because I only have some Segmentation fault, even with an empty function calling itself…

Am I missing something or is there any protection or something that prevents me for doing this?

cglacet
  • 6,638
  • 2
  • 35
  • 49
  • Related: http://stackoverflow.com/questions/1657484/can-you-give-an-example-of-stack-overflow-in-c –  Dec 05 '11 at 18:54
  • 2
    In this case, a _stack overflow_ would be the underlying reason why you get the OS-defined _Segmentation fault_ error. – ninjalj Dec 05 '11 at 18:54

4 Answers4

6

A segmentation fault means that the memory protection kicked in and prevented you from accessing memory you did not have available. This can occur for a variety of reasons, but one reason indicated is stack overflow (overflowing the stack into some other segment of memory).

Tevo D
  • 3,291
  • 20
  • 28
3

If the function is called with a negative or 0 integer argument, you'll face infinite recursion. However, the compiler likely can tail call optimize that particular function and you'd never see a stack overflow except in debug mode. The segmentation fault lies somewhere else.

Puppy
  • 141,834
  • 35
  • 244
  • 454
  • 1
    Yes, a smart compiler might optimize it into an infinite loop. However if it does not (because the OP didn't pass the appropriate -O flag for example), the given code will cause a stack overflow when called with a negative or zero argument, which will cause a segmentation fault (and so will the empty function calling itself that the OP also tried). So I don't see why you think the segmentation fault must lie somewhere else. – sepp2k Dec 06 '11 at 15:10
3

A stack overflow is a type of segmentation fault, it looks like your system has just output a generic error.

You can read more here: http://en.wikipedia.org/wiki/Segmentation_fault

Tom
  • 2,843
  • 3
  • 27
  • 32
0
Foo()

{

    float f[1024];

    Foo();

}

f is a dummy variable which will help filling stack quickly.

FrustratedWithFormsDesigner
  • 25,952
  • 31
  • 133
  • 193
rakesh
  • 1,793
  • 1
  • 14
  • 22
  • 3
    You may want to use it somehow, otherwise the optimizer may remove that array completely. – Matteo Italia Dec 05 '11 at 19:07
  • In this kind of function (and the original question), there's a reasonable chance the compiler will eliminate the recursion, depending on optimization levels, etc. – Bruce Stephens Dec 05 '11 at 22:42