[英]why am I getting segmentation fault when I alloc a 2048 * 2048 int array in c
在 C 中分配 N * N int 数组,当 N = 1024 时,它刚刚工作,当 N = 2048 时,我得到“分段错误”。 该机器是 Ubuntu 20.04 与 2GB memory。 我的 memory 不够大吗?
1 #include <stdio.h>
2
3 #define N 1024
4
5 int main()
6 {
7 int arr[N][N];
8
9 for (int i = 0; i < N; i++)
10 for (int j = 0; j < N; j++)
11 arr[i][j] = i + j;
12
13 return 0;
14 }
将 arr 的 decleration 放在 main 之外。 现在你的堆栈空间已经用完了。
宣言
int arr[N][N]
分配在memory的栈上,非常有限。
您需要在 memory 的堆部分分配
int *arr = (int*)malloc(N * N * sizeof(int));
根据 C 文档,malloc 总是分配比请求更多的 memory,并在 ZECD18173 的堆部分执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.