1

Please somebody give me a explanation of how this program cause segmentation fault and how can i exploit it?

#include<iostream>
using namespace std;

void a();
void b();

void a()
{
        cout<<"Hello World\n";
        b();
}
void b()
{
        cout<<"Hello World\n";
        a();
}

int main()
{
        a();
        return 0;
}
Dominique
  • 16,450
  • 15
  • 56
  • 112
r00tk1ll3r
  • 63
  • 1
  • 10

3 Answers3

2

The situation you describe is known as "infinite recursion", and is described in this post.

In the mentioned post, main() is calling main(), calling main(), ...

In your case, a() is calling b(), calling a(), calling b(), ...

The mentioned post shows the effect of this on the stack and gives an idea on how this is handled in the memory of your computer (using assembly).

Dominique
  • 16,450
  • 15
  • 56
  • 112
1

What you see is the effect stack overflow that happens due to the infinite recursion. While this is in theory should just print "Hello World" infinitely, the usage of a() and b() forces to store the "return address" on the stack. Typical implementations use a fixed size stack and thus it recursive calls eventually results in overflow of call stack.

Note that the "stack" is common terminology and isn't specified in the standard nor is it required to be used.

But if you optimise your code, it could simply be turned into an infinite loop without the use of functions or recursion. For example, your code can be transformed into:

#include<iostream>

int main()
{
    while (true)
        std::cout<<"Hello World\n";
}

This is allowed and valid under the "as-if" rule of C++ standard. In this case, you are not going to encounter stack overflow or segfault.

Compiling & running your code with:

g++ -Wall -Wextra -O3 test.cpp

doesn't, in fact, result in segfault.

So what you see isn't guaranteed by the standard.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

The program you write leads to an Infinite loop. In main function you call a(). a() call b() and again in b function, a() is called. So it leads to Segmentation Fault.

Sina Raoufi
  • 54
  • 2
  • 6