C language local variable and global variable size limit

When writing a program, I found a problem that a large array cannot use local variables. Global variables must be used. When summing up, I found this good article from the blogger, collection!

See code

#include <stdio.h>
int main () {
int a [1000000]; // local variable
return 0;
}

An overflow error was found after compiling and running.

#include <stdio.h>
int a [1000000]; // Global variable
int main () {
return 0;
}

Compile and run normally.

Before explaining the reasons, let's take a look at the memory occupied by a program compiled by C / C ++ divided into several parts:

1. Stack segment (stack segment): automatically allocated and released by the compiler, storing the values ​​of function parameters and local variables. Under Windows, the stack is a data structure that expands to a lower address and is a continuous area of ​​memory. This sentence means that the address of the top of the stack and the maximum capacity of the stack are predetermined by the system. Under WINDOWS, the size of the stack is 2M (some are 1M, in short, a constant determined at compile time). When the space exceeds the remaining space on the stack, overflow will be prompted. Therefore, the space available from the stack is small.

2. Heap segment: It is generally allocated and released by the programmer. If the programmer does not release it, it may be recovered by the system when the program ends. It is different from the heap in the data structure. The heap is a data structure that extends to higher addresses and is a discontinuous memory area. This is because the system uses the linked list to store the free memory address, which is naturally discontinuous, and the traversal direction of the linked list is from low address to high address. The size of the heap is limited by the virtual memory available in the computer system. This shows that the space obtained by the heap is more flexible and larger.

3. Global segment (static segment) (data segment): The storage area of ​​global variables and static variables are together, and are released by the system after the program ends. The size of the data area is limited by the system and is generally large.

4. Literal constant area: Constant strings are placed here, and are released by the system after the program ends.

5. Program code area: store the binary code of the function body.

In summary, the local variable space is very small. If we open a [1000000], it will cause a stack overflow; and the global variable space can reach 4GB under Win 32bit, so it will not overflow.

Guess you like

Origin www.cnblogs.com/silver-aircraft/p/12728363.html