【问题标题】:Heap corruption error堆损坏错误
【发布时间】:2016-02-15 02:44:54
【问题描述】:

我正在为一个班级项目工作,我去测试我已经完成的部分并得到一个堆损坏错误

#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);
}

真正奇怪的是,即使程序因为错误而崩溃,它仍然会做它应该做的一切,所以我不知道出了什么问题。

【问题讨论】:

  • 请包含您在问题中看到的确切完整错误消息。
  • 使用调试器或打印语句找出崩溃的行。

标签: c visual-studio-2012 heap-corruption


【解决方案1】:
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);

当然应该是sizeof(double)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 2017-09-12
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2010-12-07
    相关资源
    最近更新 更多