Batteries
Batteries

Reputation: 151

C: Program crashes before completing for loop

Hello Stackoverflow crew. I'm a very amateur C programmer and I'm working on a program that reads some input about wedding gifts, and then outputs information that includes the maximum gift value, the minimum gift value, the total average of the gift values, and the average of the gifts that were valued at x > 0. I've finished writing everything, but the program always seems to crash after the first loop. I've been looking at it for the past few hours, so I'm having issues finding what the error might be. Here is the code I have:

#include <stdio.h>
#include <stdlib.h>


int main() {

    //Opens the file and creats a pointer for it.
    FILE *ifp;
    ifp = fopen("gifts.txt", "r");

    //Declares the variables
    int i, j, k, l, m, n, o, p, q, x, y;
    int gift_sets, num_gifts, prices, max_value, max, avg_val, no_zero;

    //Scans the file and assigns the first line to variable "gift_sets"
    fscanf(ifp, "%d", &gift_sets);

    //Begins a for loop that repeats based on the value of gift_sets
    for (i = 0; i < gift_sets; i++) {

        printf("Wedding Gifts #%d\n", i + 1);
        printf("Gift Value\t Number of Gifts\n");
        printf("----------\t ---------------\n");

        //Scans the price values into the array prices[num_gifts]
        fscanf(ifp, "%d", &num_gifts);
        int prices[num_gifts];

        //Creates a loop through the prices array
        for (j = 0; j < num_gifts; j++){
            fscanf(ifp, "%d", &prices[j]);
        }

        //Declares a frequency array
        int freq[max + 1];

        for (k = 0; k <= max; k++) {
            freq[k] = 0;
        }

        for (l = 0; l < num_gifts; l++) {
            freq[prices[l]]++;
        }
        for (m = 0; m < max + 1; m++) {
            if (freq[m] > 0){
                printf("%d\t%d",m, freq[m]);
            }
        }

        printf("\n");

        //Zeroes the variable "max_val."
        int max_val = prices[0];

        //Loops through the array to find the maximum gift value.
        for (n = 0; n < num_gifts; n++){
            if (prices[n] > max_value)
                max_value = prices[n];
        }

        // Zeroes "min_val."
        int min_val = prices[0];

        //Finds the lowest value within the array.
        for(o = 0; o < num_gifts; o++){
            if(prices[o] !=0){
                if(prices[o] < min_val){
                    min_val = prices[o];
                 }
             }
        }

        //Calculates the total number of gifts.
        double sum_gifts = 0;
        for(p = 0; p < num_gifts; p++){
            sum_gifts = sum_gifts + prices[p];
        }

        //Calculates the average value of all the gifts.
        avg_val =  (sum_gifts / num_gifts);

        //find non zero average
        double x = 0;
        int y = 0;
        for(q = 0; q < num_gifts; q++){
            if (prices[q] != 0){
                x += prices[q];
                y++;
            }
        }

        //Calculates the average value of the gifts, excluding the gifts valued zero.
        int no_zero = x / y;

        //Prints the maximum gift value.
        printf("The maximum gift value is: $%d", max_value);
        printf("\n");

        //Prints the minimum gift value.
        printf("The minimum gift value is: $%d\n", min_val);


        //Prints the average of all the gifts.
        printf("The average of all gifts was $%.2lf\n",avg_val);

        //Prints the no zero average value of the gifts.
        printf("The average of all non-zero gifts was $%.2lf",no_zero);
        printf("\n\n\n");

    }

    return 0;
}

Thanks in advance for the help guys. As always, it's much appreciated.

EDIT: To further elaborate, the "crash" is a windows error "gifts.exe has stopped working" when executing the program. It does say at the bottom of the window that "Process returned -1073741819 <0xC0000005>"

Upvotes: 0

Views: 748

Answers (3)

paxdiablo
paxdiablo

Reputation: 882028

I'll tell you one thing you should do, straight away.

Check the return values from fscanf and its brethren. If, for some reason the scan fails, this will return less than you expect (it returns the number of items successfully scanned).

In that case, your data file is not what your code expects.

You should also be checking whether ifp is NULL - that could be the cause here since you blindly use it regardless.

One thing you'll find in IDEs is that you may not be in the directory you think you're in (specifically the one where gifts.txt is).

And, on top of that, max ill be set to an arbitrary value, so that int freq[max+1]; will give you an array of indeterminate size. If that size is less than the largest price, you'll be modifying memory beyond the end of the array with:

freq[prices[l]]++;

That's a definite no-no, "undefined behaviour" territory.

Upvotes: 2

pg1989
pg1989

Reputation: 1010

When you declare the array with the num_gifts variable, it generates assembly instructions which allocate enough space on the stack to hold num_gifts integers. It does this at compile-time. Normally this wouldn't compile, but depending on the behavior of the ms c compiler, it could compile and assume whatever value is put in num_gifts by default (maybe 0, maybe something else) is the length. When you access it, it's possible that you're trying to access an array with zero elements, which could cause an access violation.

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490328

At least at first glance, it looks like you haven't initialized max before you (try to) use it to define the freq array.

Upvotes: 1

Related Questions