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
  • 8,873
  • 4
  • 45
  • 60
  • 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,351
  • 21
  • 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
  • 144,682
  • 38
  • 256
  • 465
  • 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,973
  • 3
  • 28
  • 32
0
Foo()

{

    float f[1024];

    Foo();

}

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

FrustratedWithFormsDesigner
  • 26,726
  • 31
  • 139
  • 202
rakesh
  • 1,941
  • 2
  • 16
  • 23
  • 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