c数组中的分段错误

Segmentation fault in c array

我是 c 编程的新手。我有一个程序可以测试计算一系列 3 嵌套循环需要多少时间并在其中计算每当我尝试 运行 这段代码时它会导致分段错误。这是代码和调试信息:

#include <stdio.h>
#include <sys/time.h>
#define EXIT_SUCCESS 0;

int main(void){
  struct timeval start,end;
  gettimeofday(&start, NULL);
  int n = 100;
  int sum[n][n][n];
  int firstNum[n][n][n];
  int secondNum[n][n][n];
  for(size_t a=0;a<n;a++){
    for (size_t b = 0;b<n;b++){
      for (size_t c=0;c<n;c++){
        firstNum[a][b][c] = c;
        secondNum[a][b][c] = 1;
        sum[a][b][c] = firstNum[a][b][c] + secondNum[a][b][c];
      }
    }
  }
  gettimeofday(&end, NULL);
  double timeTook = (end.tv_sec - start.tv_sec)*1000.0;
  printf("Time took: %f\n", timeTook);
  return EXIT_SUCCESS;
}

调试信息

Program received signal SIGSEGV, Segmentation fault.
main () at /home/ayush/Desktop/Project/trial.c:16
16              secondNum[a][b][c] = 1;

我想知道是什么导致了这个错误我正在访问内存限制内的数组索引,但它仍然导致分段错误

在显示的代码中

 int n = 100;
 int sum[n][n][n];

sum 是一个 可变长度数组 (VLA)。 根据您的实现,可用于 VLA(堆栈)的大小可能非常有限(通常为 1M,数组需要 4M,3 个数组需要 12M)。

(kinda) 的一个简单解决方案仍然使用 VLA,但从更大的 space(堆)获取内存是用指针替换数组定义并分配足够的内存。

int n = 100;
int (*sum)[n][n]; // sum is a pointer to n*n arrays (kinda using VLAs)
sum = malloc(n * sizeof *sum); // allocate space for n items of n*n elements
if (sum == NULL) exit(EXIT_FAILURE); // exit if allocation failure
//...
//use sum as if it was defined as sum[n][n][n]
//...
free(sum);