fork download
  1. #include <stdio.h>
  2.  
  3. static unsigned indentation = 0;
  4. static void indent(void) { ++indentation; }
  5. static void unindent(void) { --indentation; }
  6. static void IN(void) {
  7. unsigned i = 0;
  8. for (; i < indentation; ++i) {
  9. printf(" :");
  10. }
  11. }
  12.  
  13. unsigned int crazy_factorial(unsigned int const * const n) {
  14. IN(); printf("crazy-factorial(%u @ %p)\n", *n, n);
  15. indent();
  16. unsigned int result;
  17. if (*n == 0) {
  18. result = 1;
  19. } else {
  20. unsigned int * const nextN = malloc(sizeof(unsigned int));
  21. IN(); printf("allocated memory @ %p\n", nextN);
  22. *nextN = *n - 1;
  23. result = *n * crazy_factorial(nextN);
  24. free(nextN);
  25. IN(); printf("freed %p\n", nextN);
  26. }
  27. IN(); printf("=> %u\n", result);
  28. unindent();
  29. return result;
  30. }
  31.  
  32. int main(void) {
  33. unsigned int n = 5;
  34. unsigned int result = crazy_factorial(&n);
  35. printf("crazy_factorial(%u) = %u\n", n, result);
  36. return 0;
  37. }
  38.  
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
crazy-factorial(5 @ 0xbf9991ac)
  :allocated memory @ 0x848a008
  :crazy-factorial(4 @ 0x848a008)
  :  :allocated memory @ 0x848a018
  :  :crazy-factorial(3 @ 0x848a018)
  :  :  :allocated memory @ 0x848a028
  :  :  :crazy-factorial(2 @ 0x848a028)
  :  :  :  :allocated memory @ 0x848a038
  :  :  :  :crazy-factorial(1 @ 0x848a038)
  :  :  :  :  :allocated memory @ 0x848a048
  :  :  :  :  :crazy-factorial(0 @ 0x848a048)
  :  :  :  :  :  :=> 1
  :  :  :  :  :freed 0x848a048
  :  :  :  :  :=> 1
  :  :  :  :freed 0x848a038
  :  :  :  :=> 2
  :  :  :freed 0x848a028
  :  :  :=> 6
  :  :freed 0x848a018
  :  :=> 24
  :freed 0x848a008
  :=> 120
crazy_factorial(5) = 120