LeafNode
LeafNode

Reputation: 59

Why the segmentation fault is coming

#include<iostream>
using namespace std;

class A
{
public:

virtual void f() = 0;   
};

class B: public A
{
public:

void f()
{
//   f();   //segmentation Fault
cout<<"\bB's f() called"<<endl;
f();    //recursive loop
}
};

void A:: f()
{
cout<<"\nA's f() called"<<endl;
}

   int main()
   {

     A *ptr;
     B b;

     ptr = &b;
     b.f();

  return 0;
  }

Q-> In this problem.. inside the B class f( ), if we call f( ) before "cout<<" statement it gives segmentation fault and after "cout<<" statement it gives recursive loop. Why segmentation fault is coming. Thanks in Advance :)

Upvotes: 2

Views: 201

Answers (4)

Jim Jeffries
Jim Jeffries

Reputation: 10081

You are getting a stackoverflow due to your infinite loop. You would also get one eventually with the call to f() after the cout << ... but it gets there quicker with it before. I wouldn't be surprised if the compiler does some optimisation that affects this as well.

You need to add some way of breaking out of your recursive loop.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

The recursive loop is the cause of the problems. It will never and, and the call stack will fill up.

You're missing a halting condition.

Upvotes: 0

perreal
perreal

Reputation: 97948

When you make the recursive call at the end of a function, the compiler optimizes your stack use, perhaps eliminating it. See: http://en.wikipedia.org/wiki/Tail_call. The reason of segmentation fault is stackoverflow!

Upvotes: 5

Sam DeHaan
Sam DeHaan

Reputation: 10325

Placing f() before the cout<< causes f() to be called recursively an infinite amount of times before the first cout<< happens. Both of your problems are the same conceptually, but provide different output.

Upvotes: 2

Related Questions