Memory Allocation in stack and stack.

Source: Internet
Author: User

This blog is not original

Address: http://hi.baidu.com/yangjinbo/blog/item/02e87209a38066a42eddd4ae.html

I have always had a vague understanding of this problem. I believe many of my friends also do this. I always hear that the memory will be allocated on the stack for a while and then allocated on the stack for a while, so what is the difference between them? To illustrate this problem, let's take a look at the internal memory organization.

The memory occupied by the program is divided into the following parts.

1. Stack)

The compiler automatically allocates and releases, stores function parameter values, local variable values, and so on. Memory Allocation is continuous, similar to the stack we usually call. If it is unclear, think of it as an array, and its memory allocation is continuous, that is, the allocated memory is in a continuous memory area. when we declare a variable, the compiler will automatically allocate memory at the end of the current stack.

2. Heap)

Generally, it is assigned to the programmer for release. If the programmer does not release the program, it may be recycled by the operating system when the program ends. similar to a linked list, the distribution in the memory is not consecutive. They are linked by pointers of memory blocks in different regions. once a node is disconnected from the chain, we need to release the disconnected node from the memory.

3. Global zone (static Zone) (static)

Global variables and static variables are stored in one area, and initialized global variables and static variables are stored in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. The program is released by the System

4. Text Constant Area

Constant strings are placed here. The program is released by the System

5. Code Area

Stores the binary code of the function body.

Let's look at an example.

Char C; // stack allocation
Char * P = new char [3]; // allocated on the heap and assigned the address to P;

When the compiler encounters the first instruction, it calculates its size and finds that the current stack space is larger than the space to be allocated. If the stack space is larger than the applied space, therefore, we will allocate memory space for it. Note: In this case, the internal space allocation is continuous and will be allocated after the last allocation. if the size of the stack space is smaller than the size of the applied space, the system will reveal Stack Overflow and provide corresponding exception information.

When the compiler encounters the Second instruction, P is allocated on the stack, so the internal space allocated for P is the same as the method above, but when the new key is entered, the compiler knows that this is the dynamic memory space applied by the user, so it will go to the heap to find space for allocation. note: the memory space on the heap is not consecutive. It is connected by the corresponding linked list to the internal block of its space partition. Therefore, after receiving the specified memory space allocated, it does not immediately allocate the corresponding space for it. Instead, it needs to calculate the required space and then refresh the entire column (that is, the node of the entire chain ), allocate the memory block for the first time. finally, the first address of the character array allocated on the heap is assigned to P ., at this time, we know that P now stores the first address of the character array applied in the heap, that is, the address of the Array Applied in the heap is now assigned to the pointer Variable P applied on the stack. to better illustrate the problem, see:

We can see that the first address of the dynamically allocated array on the stack is stored in the content pointed to by the pointer p.

Note: When the memory space applied for on the stack is out of the scope of the variable, the system will automatically recycle the space and apply for the space on the stack, when the corresponding scope is available, we need to explicitly call Delete to release the applied memory space. If we do not need to release the space in time, as memory fragments increase, our actual memory space will become smaller and smaller, I .e., there will be more and more isolated memory blocks. here, we know that the memory area in the heap is not continuous, and the valid memory area is connected through the linked list pointer. If we apply for a certain block
Memory, the memory block will be disconnected from the continuous (linked list) memory block. If we do not release it in time after use, then it will be isolated. Since there is no pointer pointing to it, this region will become memory fragments, so after using the dynamically allocated memory (applied through new, delete it explicitly. remember to do this...

The concepts between them are described above. For the comparison of their use, I cannot explain them intermittently. For this question, the article on the Internet described in more detail, with a professional color, the following article is part of the piece.

Application size limit

STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. Therefore, the space available from the stack is small.

Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.

Comparison of application efficiency:

The stack is automatically allocated by the system, which is faster. But programmers cannot control it.

The heap is the memory allocated by new, which is generally slow and prone to memory fragments. However, it is most convenient to use.

In addition, in windows, the best way is to use virtualalloc to allocate memory. Instead of heap or stack, it is to reserve a fast memory in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.

Storage content in heap and stack

STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note that static variables are not included in the stack.

When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.

Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.

Comparison of access efficiency

Char S1 [] = "aaaaaaaaaaaaa ";
Char * S2 = "bbbbbbbbbbbbbbbbb ";

Aaaaaaaaaaa is assigned a value at the runtime;

Bbbbbbbbbbbbb is determined during compilation;

However, in future access, the array on the stack is faster than the string pointed to by the pointer (such as the heap.

For example:

Void main ()
{
Char A = 1;
Char C [] = "1234567890 ";
Char * P = "1234567890 ";
A = C [1];
A = P [1];
Return;
}

Corresponding assembly code

10: A = C [1];

00401067 8A 4D F1 mov Cl, byte PTR [ebp-0Fh]

0040106a 88 4D FC mov byte PTR [ebp-4], Cl

11: A = P [1];

0040106d 8B 55 EC mov edX, dword ptr [ebp-14h]

00401070 8A 42 01 mov Al, byte PTR [edX + 1]

00401073 88 45 FC mov byte PTR [ebp-4], Al

The first type reads the elements in the string directly into the CL register, while the second type reads the pointer value into EDX. Reading the characters based on edX is obviously slow.

Summary:

The difference between stack and stack can be seen in the following metaphor:

Using Stacks is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it). If you are full, you can leave, without having to worry about the preparation work, such as cutting and washing dishes, as well as the cleaning and tail work such as washing dishes and flushing pots, his advantage is fast, but his degree of freedom is small.

Using heap is like making your favorite dishes by yourself. It is troublesome, but it suits your taste and has a degree of freedom.

Address: http://hi.baidu.com/yangjinbo/blog/item/02e87209a38066a42eddd4ae.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.