Reputation: 398
I am having a C program where I declare an 2d array with the size of 8,388,608 * 23. When I run the program I get the following error:
[1] 12142 segmentation fault (core dumped)
I think that the size of the array is to big.
Here is my code:
int a[8388608][23];
a[0][0] = 10;
Upvotes: 0
Views: 702
Reputation: 222828
You likely declared int a[8388608][23];
inside a function, and the C implementation attempted to allocate space on the stack.
In common C implementations on macOS, Linux, and Windows, the space designated for the stack by default ranges from 1 MiB to 8 MiB (8,388,608 bytes), depending on the operating system and whether it is a main thread or a spawned thread. Since your array exceeded the space for the stack, using it accessed memory not mapped for your process and generated a segmentation fault.
The C standard requires an implementation to have sufficient memory to execute at least some programs (C 2018 5.2.4.1) but allows there to be a limit on the memory available and does not require an implementation to provide any warning or error handling when a program exceeds the limit. It allows a program to fail and abort.
The stack size for a program can be set through linker options. However, it is generally best not to use the stack for large amounts of data. If a program needs an array throughout its entire execution, it can allocated statically by defining it outside of any function. The amount of memory needed will then be computed during link time and reserved when the program is loaded.
When a function needs a large amount of memory temporarily, it should be allocated dynamically. You can do this with malloc
:
int (*a)[23] = malloc(8388608 * sizeof *a);
if (!a)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
When the function is done with the memory, it should release it with free(a);
.
Upvotes: 2
Reputation: 341
Actually there are no limit except computers or servers RAM
from the memory perspective.
From another side compiler will not give permission to set size of each field more than long
.
int a[(1<<31)] // ok
int a[(1<<63ll)] // ok
int a[(1<<70ll)] // not ok, since in c there is no value greater than long long from integer types
Upvotes: 0