初始化2d数组后,我遇到了一个分段错误。我做了一些研究,但我不知道如何解决这个问题,有人能帮我吗?
my数组的最大长度为10000,必须由可变长度设置。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
//Set dimension of matrices
int length = 10000;
double matrix1[length][length];
//This line ends up in segmentation fault.
memset( matrix1, 0, length*length*sizeof(double));
return 0;
}发布于 2018-02-04 03:19:23
现代C编译器在堆栈上分配局部变量,堆栈的大小是有限的。您的变量double matrix1[length][length]太大,无法适应,这会导致堆栈溢出并导致分段错误。(是的,甚至在调用memset之前就会出现分段错误。)要么让matrix1成为一个全局变量,要么在malloc中使用动态内存分配。实际上,如果您使用calloc而不是malloc,那么就不需要memset了。
https://stackoverflow.com/questions/48604295
复制相似问题