hmdb
hmdb

Reputation: 323

Declare huge arrays locally in C

Why it is not good to declare huge arrays locally in C? ex: int a[1000000];

Upvotes: 6

Views: 138

Answers (5)

teppic
teppic

Reputation: 8195

The stack and the heap can be any size (the stack can be 100 times bigger than the heap if the implementation configures it that way), but generally the stack is very small, and will overflow with large allocations - especially in recursive functions.

Upvotes: 0

AbdElrhman
AbdElrhman

Reputation: 52

the stack is small (about 4kb) but heap is has more size variant on machine , allocate the array dynamically using pointer to int malloc(),

be aware of pointers and good luck

Upvotes: 2

perreal
perreal

Reputation: 97938

Although it is possible to adjust the stack space in advance to some degree, one also needs to consider the possibility of calling the same function from an execution path through the function. For example:

void a() { int a[10000000]; b(); }
void b() { d(); c(); }
void c() { a(); } 

Since this analysis is not always straightforward it can lead to overflow.

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44288

because they go onto the stack, and there is only a limited amount of space on the stack,

Upvotes: 6

Patashu
Patashu

Reputation: 21773

Because they are declared on the stack if you declare them locally - and if the stack becomes too large, you will have a stack overflow and your program will crash.

Upvotes: 5

Related Questions