读取大小无效 - 查找命令行平均值

时间:2015-09-29 13:48:28

标签: c valgrind

我试图找到命令行执行期间添加的所有数字的平均值。我得到了一些改进内存分配的valgrind错误。

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

int * arg2int(int argc, const char* argv[]) {
    int i = 1;
    int *result = malloc (sizeof (int) * (argc-1));  
    for (i = 1; i < argc; i++){
    result[i] = atoi(argv[i]);
    }
    return result;
}

float arrayAvg(int size, int *array) {
    /*STUB return 0.0/0.0; */
    int i = 0;
    float sum = 0.0f;
    for (i = 0; i <= size; i++)
    sum = sum + array[i];
    int avg = sum/size;
    return (float)avg;
}
int main(int argc, const char* argv[]) {
    int *array = arg2int(argc, argv);
    float avg = arrayAvg(argc-1, array);
    printf("%.2f\n",avg);
    return 0;
}

这是Valgrind错误,

==785== Memcheck, a memory error detector
==785== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==785== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==785== Command: ./out
==785== 
==785== Invalid read of size 4

我分析了我从一个常量字符数组的命令行条目读取到一个整数数组。但是如何删除valgrind错误。 快速注释 程序将正确执行,没有任何错误。我测试了它。这只是为了理解为什么valgrind错误会上升。

示例输出:

$ ./out 4 6 
5.00

1 个答案:

答案 0 :(得分:1)

你有两个错误:在arg2int中已经提到过@BLUEPIXY

result[i] = atoi(argv[i]); --> result[i-1] = atoi(argv[i]);

并在arrayAvg中作为@amdixon说

for (i = 0; i <= size; i++) --> for (i = 0; i < size; i++)

现在看起来像这样:

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

int * arg2int(int argc, const char* argv[]) {
    int i = 1;
    int *result = (int*)malloc (sizeof (int) * (argc-1));  

    for (i = 1; i < argc; i++)
        result[i-1] = atoi(argv[i]);

    return result;
}

float arrayAvg(int size, int *array) 
{
    int i = 0;
    float sum = 0.0f;

    for (i = 0; i < size; i++)
        sum = sum + array[i];

    return sum/size;
}
int main(int argc, const char* argv[])
{
    int *array = arg2int(argc, argv);
    float avg = arrayAvg(argc-1, array);
    printf("%.2f\n",avg);

    return 0;
}