Este programa muestra una falla de segmentación, creo que se produce una recursión infinita. ¿Me pueden sugerir la corrección?

#include <stdio.h>
int f(int n)
{
  if(n <= 1)
    return 1;
  if(n%2 == 0)
    return f(n/2);
  return f((n-1)/2) + f((n-1)/2+1);
}

/*To test above function */
int main()
{
  int a = 11;
  printf("%d", f(11));
  getchar();
  return 0;
}

preguntado el 08 de enero de 11 a las 17:01

The program prints 5 for me with no segmentation fault. That function doesn't go into infinite recursion, not for n=11 anyway. -

Initially, it gives answer and then fault occurs after a second or so. -

Would you mind giving us more information on your hardware, OS and development tools (compiler, C library version etc)? -

if it does give the answer, then it means that f() successfully returns, so no infinite recursion here. Something else is the root of the evil here, maybe getchar() but I can't imagine why. -

3 Respuestas

Why not just to trace it in debugger, and see what's goind wrong?

Respondido el 08 de enero de 11 a las 20:01

This should probably just be a comment against the question - it's not really an answer in any meaningful sense of the word. - John Parker

Well, I think it is the right answer. To any question "my code crashes" the correct answer is "Use the debugger to analyze the crash". More often than not the problem is obvious in the debugger. - Suma

This code compiles and runs just fine for me. The result is 5. Have you tried the explicit keyword to see if it is an optimization flaw? EDIT: If the problem is getchar() the problem could be your operating system at run time or your library at compile time. Is that a clean compile? What compiler are you using?

Respondido el 08 de enero de 11 a las 21:01

There is nothing wrong with this program, it doesn't give me any sort of infinite loop or seg fault (and since you have the <=1 condition, the program will not crash out for sure). Something tells me that your machine here is faulty for some reason... maybe lack of memory or confilcting programs? Or even compiler freaking out? (that one already happened to me). Try to run the code on other machine if possible and find out if it still gives you seg fault or not

Respondido el 08 de enero de 11 a las 20:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.