8 Valgrind 的无效写入大小

Invalid Write Size of 8 Valgrind

我正在编写一个函数来解析 .csv 文件,但我在使用 valgrind 时遇到错误。具体是这样的:

==5450== Invalid write of size 8
==5450==    at 0x404FA0: parse_exemplars (util.c:568)
==5450==    by 0x40508E: get_test_and_train_data (util.c:595)
==5450==    by 0x402737: setup (pony_gp.c:727)
==5450==    by 0x4027E5: main (pony_gp.c:761)

这是带有错误行的代码:

csv_reader *reader = init_csv(file_name, ',');

double **fitness_cases, *targets;
int num_columns = 122;
int num_lines = 121;

// leave space for NULL at end
fitness_cases = malloc(sizeof(double **) * num_lines);
for (int i = 0; i < num_lines; i++) {
    fitness_cases[i] = malloc(sizeof(double *));

    for (int k = 0; k < num_columns; k++) {
        fitness_cases[i] = malloc(sizeof(double) * (num_columns - 1));
    }
}

// leave space for NAN at end
targets = malloc(sizeof(double) * (num_lines));

csv_line *row;
int f_i = 0;
int t_i = 0;

while ((row = readline(reader))) {
    int i;
    for (i = 0; i < num_columns; i++) {
        if (i == num_columns - 1) {
            targets[t_i++] = atof(row->content[i]);
        }
        else {
            fitness_cases[f_i][i] = atof(row->content[i]);
        }
    }

    fitness_cases[f_i][i-1] = (double)NAN; //<----- This is where it says the error is, line 568.
    f_i++;
}

每当我检查 fitness_cases[f_i][i-1] 的大小时,我总是得到与 (double)NAN 大小相同的值,所以我猜它来得早在函数中?

github 页面的 link 是(我问的这个功能目前在 repo 上没有更新):https://github.com/dyingpie1/pony_gp_c

fitness_cases[f_i][i-1] = (double)NAN; 

此处 i-1 的值将是 num_columns -1 但因为您已将 space 分配为

fitness_cases[i] = malloc(sizeof(double) * (num_columns - 1));

第二个数组下标的最大索引可以少一个,即num_columns - 2,否则你会越界

例如

fitness_cases[i] = 3 * sizeof(double);

fitness_cases[i][0]fitness_cases[i][1]fitness_cases[i][2] 有效,fitness_cases[i][3] 超出范围,将导致无效写入,如 valgrind

所示