Alloc N * N int array in C, When N = 1024, It Just Workd, When N = 2048, I get "segmentation fault ". The machine is Ubuntu 20.04 with 2GB memory. Is my memory not big enough?
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 }
Put the decleration of arr outside of main. As it is now you are running out of stack space.
The declaration
int arr[N][N]
Is allocated on the stack of memory, which is very limited.
You need to allocate on the heap part of the memory
int *arr = (int*)malloc(N * N * sizeof(int));
By the C documentation, malloc always allocate more memory than the request and do this in the heap part of the memory.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.