4

Consider a tail recursive factorial implementation in C:

#include <stdio.h>

unsigned long long factorial(unsigned long long fact_so_far, unsigned long long count, unsigned long long max_count){

if (max_count==0 || max_count==1 || count >= max_count)
        return fact_so_far;
else
{
        printf("%llu  %p \n", count, &factorial);
        return factorial(fact_so_far * count, ++count, max_count);
}

}


int main(int argc, char **argv)
{
        unsigned long long n;
        scanf("%llu", &n);
        printf("\n Factorial %llu \n",factorial(1,0,n));
        return 0;

}

I place a breakpoint in 'factorial' and I run the above under 'gdb'. The breakpoint is never hit.

Assuming that its tail call optimised (I have compiled it using gcc -O2), it should hit the breakpoint, atleast once, IIRC.

EDIT: I get the final result without hitting any breakpoint. For eg,

(gdb) b factorial
Breakpoint 1 at 0x8048429: file factorial-tail.c, line 3.
(gdb) run
Starting program: /home/amit/quest/codes/factorial-tail 
5
0  0x8048420 
1  0x8048420 
2  0x8048420 
3  0x8048420 
4  0x8048420 

 Factorial 120 

Program exited normally.
(gdb) 

Where am I going wrong?

2 Answers2

3

Works fine for me. You are membering to use the -g flag to add debug info when you compile? And you are remembering that you have to enter a number to calculate the factorial of?

  • I didn't add the '-g' option earlier. But now I did it. No changes in behaviour. And yes, I have entered the number to find the factorial of. I have EDITED the question to make it clearer. –  May 18 '09 at 11:40
  • I''ve tried it with both gcc 3.4.5 anf g++ 4.4.0, optimised and unoptimised, and I always hit the breakpoint. Does it work for you unoptimised? And what platform and gcc/gdb versions are you using? –  May 18 '09 at 11:49
  • Yes. unoptimised code works just fine! Hits the breakpoint as many number of times, I expect.My gcc --version reads 4.3.5-ubuntu. –  May 18 '09 at 11:52
  • May just be quirk of the combo of the versions of gcc & gdb that you are using. You don't normally want to debug optimised code, in any case. Sorry I can't help further. –  May 18 '09 at 11:56
3

It could be that the factorial function is inlined into main. If this happens, there will be a second copy of factorial used for calls from other .c files; that's where your breakpoint was. Try passing -fno-inline.

bdonlan
  • 224,562
  • 31
  • 268
  • 324