简体   繁体   中英

C Segmentation Fault With Printf() and Scanf()

I'm new to C, and I'm getting a segmentation fault that I can't understand. I have the following program, which attempts to calculates the number of factors of a strictly positive number:

#include <stdio.h>
#include <math.h>

int numberOfFactors (int number, int factor) {
    if (number % factor == 0) {
        number = number/factor;
        return numberOfFactors(number, factor) + 1;
    } else {
        return 0;
    }
}

int check (int x) {
    if (x>0) {
        return 1;
    } else {
        return 0;
    }
}

int main(void) {
    int number;
    printf("Please enter a positive integer n such that n >= 1: ");
    scanf("%d", &number);
    if (check(number)){
        int i;
        for (i=1; i<=number; i++) {
            int factors;
            factors = numberOfFactors(number, i);
            printf("%d^%d ", i, factors);
        }
    }
    return 0;
}

The segmentation fault occurs immediately after entering an integer and ENTER after these lines in main():

printf("Please enter a positive integer n such that n >= 1: ");
scanf("%d", &number);

What in these lines is causing the segmentation fault, and what can I do to avoid it?

Your recursion doesn't stop if you try to divide out factor one.

Just let factor never be 1:

    for (i=2; i<=number; i++) {
        int factors;
        factors = numberOfFactors(number, i);
        printf("%d^%d ", i, factors);
    }

I should say WHY it segfaults: It's because every function call pushes the current program counter (the position in your program where you currently stand) and function arguments on the stack (aka call stack), where the stack is a relatively small memory block used for, well, function calling and local variables.

So if you are pushing your stack too hard, it will fall over. End of game, aka segfault ;)

You probably have a problem with this recursion:

int numberOfFactors (int number, int factor) {
    if (number % factor == 0) {
        number = number/factor;
        return numberOfFactors(number, factor) + 1;
    } else {
        return 0;
    }
}

Change your numberOfFactors to something like:

int numberOfFactors (int number)
{
    int i=1;
    int ret=0;
    for(;i<=number;i++) {
        if (number%i == 0) {
            ret++;
        }
    }
    return ret;
}

And then, change this portion:

if (check(number)){
    int i;
    for (i=1; i<=number; i++) {
        int factors;
        factors = numberOfFactors(number, i);
        printf("%d^%d ", i, factors);
    }
}

To something simpler like:

if (check(number)){
    factors = numberOfFactors(number);
    printf("%d^%d ", number, factors);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM