Domanda

I have the following C program compiled in Microsoft Visual Studio Express 2012:

int main() {
   int a[300000];
   return 0;
}

This crashes with a stack overflow in msvcr110d.dll!__crtFlsGetValue().

If I change the array size from 300,000 to 200,000 it works fine (in so much as this simple program can be said to 'work' since it doesn't do anything).

I'm running on Windows 7 and have also tried this with gcc under Cygwin and it produces the same behaviour (in this case a seg fault).

What the heck?

È stato utile?

Soluzione 2

Because it's being allocated on the stack and the stack has a limited size, obviously not large enough to hold 300000 ints.

Use heap allocation a la malloc:

int* a = malloc(sizeof(int) * 300000);
// ...
free(a);

The heap can hold a lot more than the stack.

Altri suggerimenti

There are platform-specific limits on the size of the space used by automatic objects in C (the "stack size"). Objects that are larger than that size (which may be a few kilobytes on an embedded platform and a few megabytes on a desktop machine) cannot be declared as automatic objects. Make them static or dynamic instead.

In a similar vein, there are limits on the depth of function calls, and in particular on recursion.

Check your compiler and/or platform documentation for details on what the actual size is, and on how you might be able to change it. (E.g. on Linux check out ulimit.)

The size of thread stacks is traditionally limited by operating systems because of a finite limit to the amount of virtual address space available to each process.

As the virtual address space allocated to a thread stack can't be changed once it is allocated, there is no strategy other than to allocate a fairly large, but limited, chunk to each thread - even when most threads will use very little of it.

Similarly, there is a finite limit also on the number of threads a process is allowed to spawn.

At a guess, the limit here is 1MB, and Windows then limits the number of threads to - say - 256, this means that 256MB of the 3GB virtual address space available to a 32-bit process is allocated to thread stacks - or put another way, 1/12th.

On 64-bit systems, there is obviously a lot more virtual space to play with, but having a limit is still sensible in order to quickly detect - and terminate - infinite recursion.

Local variables claim space from the stack. So, if you allocate something large enough, the stack will inevitably overflow.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top