嘿我想弄清楚为什么下面的代码从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);
}
答案 0 :(得分:2)
正如我所看到的,对于initialize_array()
函数,对于for
循环,第一次迭代,i
为0
,并且您正在执行< / p>
array[i-1] = i;
转换为
array [-1] = ....
这是非法的。
您可以使用基于0的索引方案的默认C数组属性来修复此问题。像
这样的东西 for(int i = 0; i < size; ++i)
{
array[i] = i;
}