【发布时间】:2018-01-11 15:11:43
【问题描述】:
嘿,我想弄清楚为什么下面的代码会从 Valgrind 那里得到无效写入大小错误:array[i-1] = I;
我现在真的不明白为什么我的 allocate_array 函数不起作用。我尝试了很多东西。
还有几个错误,但我只是想先检查一下为什么这条线是错误的,或者为什么我的数组没有分配。
希望你能帮我找出我的错误。
#include<stdio.h>
#include<stdlib.h>
//Programm to check Gaussian function
int read_number_from_stdin(int* value) {
printf("Number for the Gaussian Function: ");
int return_value = scanf("%d", value);
if (return_value == 0) {
while (fgetc(stdin) != '\n')
;
}
if (return_value == EOF) {
return_value = 0;
}
return return_value;
}
int read_number_from_string(char* string, int* value) {
printf("Reading input...\n");
int return_value = sscanf(string, "%d", value);
if (return_value == 0 || return_value == EOF) {
printf("\t... Error your input is not a Number!\n");
return_value = 0;
} else {
printf("\t... Number %d read and saved.\n", *value);
}
return return_value;
}
int* allocate_array(int* size) //allocating memory for the array
{
int* result = (int*) malloc(sizeof(int) * (*size));
return result;
}
void initialize_array(int array[], int size) {
for (int i = 0; i < size; i++) {
array[i] = i+1;
}
}
int compute_sum_and_place_in_first_elem(int array[], int* size) {
int sum_array = 0;
for (int i = 0; i < *size; i++) {
sum_array += array[i];
}
return sum_array;
}
void free_memory(int array[], int* N) {
free(array);
free(N);
}
int main(int argc, char* argv[]) {
int* N = malloc(sizeof(int));
if (argc == 1) {
while (read_number_from_stdin(N) != 1)
;
} else if (argc == 2) {
if (read_number_from_string(argv[1], N) == 0) {
printf("Error: No valid number!\n", argv[1]);
return -1;
}
} else {
printf("No valid number!\n");
return -1;
}
int* array = allocate_array(N); //allocate via function
initialize_array(array, *N); //initialize the array up to n
int result = compute_sum_and_place_in_first_elem(array, N);
int result_gauss = ((*N + 1) * (*N) / 2);
if (result == result_gauss) {
printf("Gauss was right your calculations match with his function");
} else {
printf(
"\nGauss was not right!\n"
"The summ of %d is %d and therefore not equal to(%d+1)*%d/2\n\n",
*N, result, *N, *N);
}
//free memory
free_memory(array, N);
}
【问题讨论】:
-
当
i等于0 时考虑array[i-1]。 -
然后看看
free_memory,它以return开头。我们如何联系free-calls? -
请注意,
while (fgetc(stdin) != '\n');是文件末尾的无限循环。 -
请注意,
i <= size总是为有经验的 C 编码器敲响警钟。 99% 的时间你的意思是i < size。提醒:包含 3 个条目的数组的索引为 0,1,2 -
顺便说一句 - +1 使用 valgrind