I am really new to C, so I am sorry if this is a absolute beginner question, but I am getting a segmentation error when I am building large array, relevant bits of what I am
numbs
is a Variable Length Array (VLA).
VLAs can be created only in block scope (i.e., inside a function). They're allocated like any other local variable, typically on the stack.
Unfortunately, the language doesn't provide a way of detecting or handling allocation failures for local variables. If you allocate too much memory, your program will crash if you're lucky.
Large objects whose size isn't known at compile time should be allocated via malloc()
(which means you need to keep track of the allocation and release them with free()
).
Incidentally, there's no need to cast arr_size
to int
. And both ust_limit
and arr_size
should be of type size_t
(defined in <stddef.h>
).
Example:
unsigned long long numbs = malloc(arr_size * sizeof *numbs);
/* And later, when you're done with it */
free(numbs);
You array stores on stack frame, which has a limit to its size, use malloc
instead.
unsigned long long *numbs = malloc(arr_size * sizeof(long long));
// don't forget to free after use
free(numbs)
You're consuming too much stack. The limit is platform dependent.
The exact limit depends on the OS. These limits can be changed to some extent on some operating systems .
For large amounts of memory, you should be using the head with malloc
and/or calloc
(and free
).
You are most likely getting a stack overflow, since you are creating a very large array on the stack. To avoid this, allocate the memory dynamically:
unsigned long long *numbs = malloc(arr_size * sizeof(unsigned long long));
Later, when you are finished with the array, free it again:
free(numbs);