how I can debug this with gdb?

R

rolo

Im trying to do a recursive algoritm and debug it. My problem is that I got
segfault if I run it withous optimizing it with the compiler, since I want
to debug it. If I use a smaller number it runs ok, but im interested on
bigger numbers.

Can anyone help me out and explain why this happens?
heres a sample code: (it doesn't matter if I use template or not, I got the
same results)

If I optimize it with -O3 or -O2 the program runs fine and returns the
expected 0.

#include <iostream>

using namespace std;

template <class T>
inline T one_less(T tmp){
if(tmp > 0) return one_less(tmp - 1);
else return 0;
}//one_less(T tmp){

int main(void){
unsigned long int tmp = 100000;
cout << one_less(tmp) << endl;
cin.get();
return 0;
}//main(void){




~ Let us linux ~
 
A

Artie Gold

rolo said:
Im trying to do a recursive algoritm and debug it. My problem is that I got
segfault if I run it withous optimizing it with the compiler, since I want
to debug it. If I use a smaller number it runs ok, but im interested on
bigger numbers.
Indeed.

Can anyone help me out and explain why this happens?
heres a sample code: (it doesn't matter if I use template or not, I got the
same results)

Sure. Consider the code below. How many recursive invocations of
`one_less' are there going to be?

You're likely `blowing your stack' (hitting an OS limitation).
If I optimize it with -O3 or -O2 the program runs fine and returns the
expected 0.

<OT>
Your compiler (in optimizing mode) evidently performs an optimization
called `tail-call elimination' which replaces a certain class of
recursive calls by a simple loop. I would advise you to search the web
for more details.
#include <iostream>

using namespace std;

template <class T>
inline T one_less(T tmp){
if(tmp > 0) return one_less(tmp - 1);
else return 0;
}//one_less(T tmp){

int main(void){
unsigned long int tmp = 100000;
cout << one_less(tmp) << endl;
cin.get();
return 0;
}//main(void){
HTH,
--ag
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top