Reputation:
The following program crashes when I try to print the value of v
. I'm trying to understand why. Any suggestions?
#include <stdio.h>
int main() {
int v[5000000];
printf("\n\nv = %p", v);
return 0;
}
EDIT: the program does not segfault if instead of allocating 5000000 elements I allocate 500000 or less.
EDIT(2): increasing the stack size solved the problem. On Linux, I increase the stack size after reading the answer of stephane-rouberol (using ulimit -s <some_large_number>
).
Upvotes: 0
Views: 477
Reputation: 38163
Congrats, you have stack overflow :)
Find a way to increase the size of the stack or just allocate the array dynamically:
int* v = malloc( 5000000 * sizeof *v);
/* do something */
free( v );
Upvotes: 1
Reputation: 213740
As others have said, stack overflow. To understand why and when the code actually crashes, this is what goes on between the lines:
Upvotes: 0
Reputation: 4384
Stack overflow !
See ulimit -s
if you use bash
or limit stacksize
if [t]csh
Or instead of using stack, you can use the heap with malloc
Upvotes: 1
Reputation: 36082
The stack size of a program is dependent on compiler switches and defaults are different from OS to OS. In your case it sounds as if the stack is too small to accomodate that large number. See your compiler(linker) switches to increase stack size.
Upvotes: 0
Reputation: 22890
You already have the cause. 5000000
is too big to handle for the program stack where v
will be allocated. You should allocate it dynamically with malloc
.
Upvotes: 0