Reputation: 1757
I'm wondering why this works up to a size of 1e8. For sizes larger than 1e8, the compiler says "size too large".
#include <stdio.h>
int main() {
printf("allocating...\n");
static float m[(int)1e8];
printf("done\n");
}
While this works only up to 1e5. If size is set to 1e6, it does compile fine, but crashes in runtime even before the first line is printed.
#include <stdio.h>
int main() {
printf("allocating...\n");
float m[(int)1e5];
printf("done\n");
}
What are these limits? And why the static
has a higher limit?
edit: platform is MinGW64 in windows7. Haven't tested it in linux yet.
Upvotes: 1
Views: 896
Reputation: 168
Static declarations are usually allocated as soon as the program starts, and are still allocated for as long as your program runs, while non-static declarations are usually stored on the stack, and may be reused as soon as the function terminates. This is probably why these two allocations behave differently.
I'd like to say that in the second case, the fact that your program crashes is linked to how your OS handles the stack. But I can't be sure
Upvotes: 2
Reputation:
In terms of C, an object with static storage duration lives for the whole execution time of the program, while one with automatic storage duration (which is the default in a function scope) only lives within its scope. The immediate consequence is that you will only ever have one instance of the static version, while an automatic object is created each time you call the function. C doesn't have anything to say about size limits.
But of course, there's a simple explanation: Most implementations of C use the stack to store automatic variables. Every function call gets a stack frame of its own, so this assures every function works with its own instance of a "local variable". Operating systems limit the total size of the stack, and that's the limit you're hitting here. On the other hand, an object with static storage duration is defined directly in your executable, this memory will be taken from the OS upon start of your process.
Upvotes: 5