Search code examples
cfunctionsegmentation-faultscanfcalling-convention

Segmentation fault with method in C


#include<stdio.h>
int calc_perc(int r){

        float A, B, C, OTHER;
        int fullSections, leftover;
        const int FULLCLASS = 25;

        fullSections = r/FULLCLASS;
        leftover = r - (FULLCLASS*fullSections);
        A = r*0.30;
        B = r*0.25;
        C = r*0.15;
        OTHER = r*0.30;

        printf("\nEnrollment: %d students\n", r);
        printf("Full sections: %d\n", fullSections);
        printf("Left over: %d students\n", leftover);

        printf("\n      Students expected to recieve an A: %0.2f ", A);
        printf("\n      Students expected to recieve a B: %0.2f ", B);
        printf("\n      Students expected to recieve a C: %0.2f ", C);
        printf("\n      Students expected to recieve some other grade: %0.2f\n\n", OTHER);

        printf("=======================================\n\n");
}

int main(void)
{

        int students1, students2, students3;

        printf("Elijah Grote\n");
        printf("\nEnter three enrollments on one line: ");
        scanf("%d %d %d", students1, students2, students3);
        calc_perc(students1);
        calc_perc(students2);
        calc_perc(students3);
        return 0;
}

The error I think happens either in calc_perc or scanf... But I can't figure out which and why it is doing it... It compiles clean, but when I input the numbers for students 1, 2 and 3, it gives me a segmentation fault. I use Unix and when I do a.out and input this after it asks for 3 numbers: 56 ^H^H it prints out the right format, but does not have the right numbers... something to do with wrong memory allocation or a bad pointer?

Appreciate any help,

Thanks


Solution

  • Function scanf requires the address of each target variable (how else would it set it into something?).

    Change this:

    scanf("%d %d %d", students1, students2, students3);
    

    To this:

    scanf("%d %d %d", &students1, &students2, &students3);
    

    As a side-note, you've declared function calc_perc to return an int, but it does not return anything.