Thread: Why this code gives a segmentation fault error?

  1. #1
    Registered User
    Join Date
    Nov 2011
    Location
    Laramie, Wyoming
    Posts
    8

    Why this code gives a segmentation fault error?

    Hi there,

    I don't know why this code gives a segmentation fault error,
    Code:
    # include <stdio.h>
    # include <math.h>
    
    long move(int GoRight, int GoDown) {
        long i = 0;
        if (GoRight > 0) {
            i = i + 1 + move(GoRight - 1, GoDown);
        }
        if (GoDown > 0) {
            i = i + 1 + move(GoRight - 1, GoDown);
        }
        return i;
    }
    
    int main(void) {
        printf("%ld\n", move(2, 2));
    
        return 0;
    }
    while the one below doesn't:
    Code:
    # include <stdio.h>
    # include <math.h>
    
    long move(int GoRight) {
        long i = 0;
        if (GoRight > 0) {
            i = i + 1 + move(GoRight - 1, GoDown);
        }
        return i;
    }
    
    int main(void) {
        printf("%ld\n", move(2));
    
        return 0;
    }
    Some hints, please?

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    3,745
    Because the first one is infinite recursion because it has no stopping condition for GoDown above zero.

    Tim S.

  3. #3
    Registered User
    Join Date
    Nov 2011
    Location
    Laramie, Wyoming
    Posts
    8
    Thank you very much Tim. I didn't spot that typo. The problem is now fixed.

    Xianwen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation Fault (Can Someone look at my code?)
    By jtkosh in forum C Programming
    Replies: 12
    Last Post: 09-27-2011, 07:06 PM
  2. What is Segmentation fault and why do we get this error?
    By sumit180288 in forum C Programming
    Replies: 2
    Last Post: 09-12-2011, 12:05 AM
  3. Segmentation fault Error
    By unknown_ in forum C Programming
    Replies: 7
    Last Post: 03-21-2010, 01:32 PM
  4. Segmentation fault error
    By ashok449 in forum C Programming
    Replies: 31
    Last Post: 03-02-2008, 02:13 AM
  5. Help with code segmentation fault
    By blindleaf in forum C Programming
    Replies: 2
    Last Post: 04-10-2003, 03:00 PM