c - 初始化数组时 C 中的段错误

标签 c arrays segmentation-fault

我试图在一个单独的函数中动态创建一个数组,并在该数组内存储一些变量,我遇到了以下问题:当我编写时,怎么会这样;

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

void foo(int **arr, int N) {
  *arr = malloc(sizeof(int));

  for (int index = 0; index <= 4; index++) {
    *arr[index] = 1;
  }
}

int main() {
  int *arr; 
  foo(&arr, 5);

  for (int bar = 0; bar <= 4; bar++) {
    printf("%d ", arr[bar]);
  }
}

我得到这个输出;

exited, segmentation fault

但是,当我运行以下命令时;

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

void foo(int **arr, int N) {
  *arr = malloc(sizeof(int));
}

int main() {
  int *arr; 
  foo(&arr, 5);

  for (int index = 0; index <= 4; index++) {
    arr[index] = 1;
  }

  for (int bar = 0; bar <= 4; bar++) {
    printf("%d ", arr[bar]);
  }
}

我得到这个输出;

1 1 1 1 1

我一直在试图弄清楚如何修复第一段代码以使其正常工作,但我似乎不知道该怎么做。任何有助于至少理解为什么会发生段错误的帮助将不胜感激。

最佳答案

这里发生的一些事情都是重要的细节。

Evgeny 是正确的,您需要分配 N 个 sizeof int 的东西。否则你的程序是错误的,并且会写入无效的内存位置。

花了几分钟时间才找到段违规的原因。我在整个代码中添加了 printf 语句,以便能够查看发生段冲突的位置。它表明将 1 分配给数组元素就是发生这种情况的地方。

然后我怀疑绑定(bind)/顺序是问题所在,因此在 *arr 两边加上括号,以非常清楚地表明这是意图。此后,段违规就消失了。我还将初始化更改为索引,以便可以轻松验证分配结果。

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

void foo(int **arr, int N) 
{
    *arr =(int *) malloc(sizeof(int) * N);

    for (int index = 0; index < N; index++)
    {
        printf("before assignment\n");
        (*arr)[index] = index;
        printf("after assignment\n");
    }
}

int main() 
{
  int *arr; 
  foo(&arr, 5);

  for (int bar = 0; bar < 5; bar++) 
  {
    printf("%d ", arr[bar]);
  }
}

简而言之,一种有用的快速但肮脏的技术是插入一堆 printfs 来帮助缩小问题发生的范围。

关于c - 初始化数组时 C 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58467946/

相关文章:

javascript - 在 Javascript 对象数组中映射和缩减数组

c - 反转函数数组字符串

c - "Cannot allocate memory"在 C 中使用 shmat 命令的共享内存问题

c++ - 如何编译c++而不包括cstdio和其他c标准库

c++ - 了解 C++ 中的 clock() 和 CLOCKS_PER_SEC

c - 为什么我得到 0 作为输出?你能找出错误吗?

c - 避免段错误

C 库检查器(类似反射器)?

c++ - 如何检查我打开的文件是否用于在 C 中读取或写入

c++ - 通过转换 OpenCV UMat 的句柄来实例化 OpenCL cl_mem