cglacet
cglacet

Reputation: 10912

How can I get a stack overflow in C++ and Unix?

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?

Upvotes: 2

Views: 220

Answers (4)

rakesh
rakesh

Reputation: 2051

Foo()

{

    float f[1024];

    Foo();

}

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

Upvotes: 0

Tevo D
Tevo D

Reputation: 3381

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).

Upvotes: 6

Tom
Tom

Reputation: 3063

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

Upvotes: 3

Puppy
Puppy

Reputation: 146910

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.

Upvotes: 3

Related Questions