c - 学习 C 试图通过函数找出这个 malloc 的东西

标签 c arrays memory valgrind

嘿,我想弄清楚为什么以下代码在行中从 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);
}

最佳答案

如我所见,对于 initialize_array() 函数,对于 for 循环,第一次迭代,i 0,你正在执行

   array[i-1] = i;

转化为

   array [-1] = ....

这是非法的。

您可以使用基于 0 的索引方案的默认 C 数组属性修复该问题。有点像

    for(int i = 0; i < size; ++i)
    {
        array[i] = i;
    }

关于c - 学习 C 试图通过函数找出这个 malloc 的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48210234/

相关文章:

javascript - 如何使数组中的最低值 = x 和最高值 = y,同时使所有其他值相对

Python:计算成对距离会导致内存错误

java - java内存分配

c - 你知道哪些避免条件分支的技巧?

c - Linux中 "system"和 "exec"的区别?

c - 屏蔽最高有效位

javascript - 具有条件的数组的总和

javascript - 使用 JavaScript/AngularJS 将数组转换为对象

c++ - 确定运行时参数的性质

可以在 GCC 中将 std=c99 设置为默认值吗?