zman419
zman419

Reputation: 41

Heap corruption error

I'm working away on a project for class and I went to test the part I had completed and got a heap corruption error

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

double findMean(double a[], unsigned int size)
{
    double total = 0;
    double mean;
    for (unsigned i = 0; i < size; ++i)
    {
        total = total + a[i];
    }
    mean = total / (double)size;
    return mean;
}

int main(int argc, char *argv[]) 
{
    int size;     // the number of elements 
    double *array;   // pointer to the array, will be allocated by malloc 

    if (argc < 2) 
    {
        // if argc is 1, there are no command line arguments 
        printf("no arguments\n");
        return 1;
    }
    size = atoi(argv[1]);  // convert the string argument to a number 

    if (size > argc - 2) 
    {
        // there should be exactly size+2 strings on the command line including the program name argv[0] and the number of elements argv[1].
        printf("%d missing arguments\n", size - (argc - 2));
        return 2;
    }
    if (size < argc - 2) 
    {
        // here there are too many command line arguments 
        printf("%d extra arguments\n", (argc - 2) - size);
        return 3;
    }
    // allocate memory for the array: size elements, each having the size of an int */
    array = malloc(sizeof(int) * size);
    if (array == NULL) 
    {
        // if memory cannot be allocated, malloc() returns a NULL pointer 
        printf("cannot allocate array\n");
        return 4;
    }
    //convert the command line arguments from 2 to size+1 to doubles and store them into the array

    for (int i = 0; i < size; i++)
    {
        array[i] = strtod(argv[2 + i], NULL);
    }

    printf("Results:");

    double min = array[0]; //Element zero of sorted array will be minimum
    printf("\nmin = %.3lf ", min);
    double max = array[size - 1];
    printf("\nmax = %.3lf", max);
    double mean = findMean(array, size);
    printf("\nmean = %.3lf", mean);

    free(array);
}

The really weird thing is, even though the program crashes because of the error, it still does everything it's supposed to do, so I don't know what's going wrong.

Upvotes: 0

Views: 110

Answers (1)

dxiv
dxiv

Reputation: 17638

double *array;   // pointer to the array, will be allocated by malloc 

/* ... */

// allocate memory for the array: size elements, each having the size of an int
array = malloc(sizeof(int) * size);

That should be sizeof(double) of course.

Upvotes: 2

Related Questions