unsigned long long factor...">

Doubt about optimized tail code under "gdb"

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 put a breakpoint in the "factorial" and I run the above under "gdb". A breakpoint never hits.

Assuming its tail call is optimized (I compiled it with gcc-O2), it should hit the breakpoint at least once, IIRC.

EDIT: I get the final result without clicking any breakpoints. For example,

 (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
c gcc tail-recursion gdb
May 18 '09 at 11:23
source share
2 answers

Perhaps the factorial function is included in the main. If this happens, a second copy of the factorial will appear, used for calls from other .c files; that where your breakpoint was. Try passing -fno-inline.

+2
May 19 '09 at 2:10
source share

Works great for me. Are you involved in using the -g flag to add debugging information when compiling? And do you remember that you need to enter a number to calculate the factorial?

+3
May 18 '09 at 11:29 a.m.
source share



All Articles