C memory allocation method [reprint]

Source: Internet
Author: User
Tags stack pop

In C , memory is divided into 5 zones, each of which are heaps, stacks, free storage, global / static storage, and constant storage.

  A Brief introduction:

1 . Stacks, which are the stores of variables that are allocated by the compiler when needed, are automatically cleared when it is not required. The variables inside are usually local variables, function parameters, and so on.

  2 . Heap, which is the memory blocks allocated by New , their release compiler does not go to the tube, by our application to control, generally a new will correspond to a delete. If the programmer does not release it, the operating system will automatically recycle after the program finishes.

  3 . The free storage area , which is the memory blocks allocated by malloc , is very similar to the heap, but he ends his life with No.

  4 . Global / static storage, global variables and static variables are allocated in the same piece of memory, in the previous C language, the global variables are divided into initialized and uninitialized, in C There is no such distinction, Together they occupy the same chunk of memory.

  5 . Constant storage , which is a more special store, they are stored in constant, not allowed to modify (of course, you have to be able to modify by improper means, and many methods, in the "Const Thinking" article, I gave 6 Methods)

Two Clearly differentiate heaps and stacks

On bbs , Heap and stack of the problem, seems to be an eternal topic, this shows that the beginner is often confused, so I decided to take his first surgery.

  first, let's give an example:  .

void F () {int* p=new int[5];}

This short sentence contains heaps and stacks, see new, we should first think that we allocated a heap of memory, then pointer p ? He allocates a stack of memory, so the meaning of this sentence is: In the stack memory is stored in a pointer to a heap of memory p. The program will first determine the size of the memory allocated in the heap, then call operator new to allocate memory, and then return the first address of the memory, put in the stack, his assembly code under VC6 is as follows:

00401028 Push 14h

0040102A call operator new (00401060)

0040102F Add esp,4

00401032 mov dword ptr [Ebp-8],eax

00401035 mov eax,dword ptr [ebp-8]

00401038 mov dword ptr [Ebp-4],eax

Here, we do not release the memory for the sake of simplicity, then how to release it? Is it delete p ? Oh, wrong, it should be delete []p, this is to tell the compiler: I delete the array,VC6 will be based on the corresponding Cookie information to do the work of releasing memory.

  Well, let's go back to our topic: What's the difference between heaps and stacks?

  The main differences are from the following points:

  1, different management methods;

  2, the space size is different;

  3, can produce different fragments;

  4, the growth direction is different;

  5, the distribution method is different;

  6. Different efficiency of distribution ;

  Management mode: for the stack, is automatically managed by the compiler, without our manual control, for the heap, release work by the programmer control, easy to produce memory leak.

 space size: Generally speaking, in the system, the heap memory can reach 4G space, from this point of view heap memory is almost no limit. But for the stack, generally there is a certain amount of space, for example, under the VC6 , the default stack space size is 1M(seems to be, not clear). Of course, we can modify:

Open the project and proceed to the following menu:project->setting->link, select Outputin Category , then Sets the maximum value and commitof the stack.

Note: The minimum value of the reserve is 4Byte;commit is kept in the virtual memory of the page document, his large configuration will allow the stack to open up a larger value, may increase the memory overhead and startup time.

  fragmentation problem: for the heap, frequent new/delete is bound to cause memory space discontinuity, resulting in a large number of fragments, so that the program efficiency is reduced. For the stack, there is no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there will never be a memory block from the middle of the stack pop-up, before he pops up, in the back of his upper stack content has been ejected, a detailed reference to the data structure, here we are no longer one by one discussion.

 Growth direction: for the heap, the direction of growth is upward, that is, to the memory address of the direction of increase, for the stack, his growth direction is downward, is to reduce the memory address in the direction of growth.  .

 allocation method: The heap is dynamically allocated and there are no statically allocated heaps. Stack has 2 Allocation method: Static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is assigned by the alloca function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is released by the compiler without our manual implementation.

allocation efficiency: The stack is the data structure provided by the machine system, the computer will support the stack at the bottom: allocate the address of the special register storage stack, the stack stack has a special instruction execution, which determines the efficiency of the stack is high. The heap is provided by the C + + function library, and his mechanism is complex, for example, in order to allocate a piece of memory, the library function will search the heap memory for a sufficient amount of available space in a certain algorithm (the specific algorithm can refer to the data structure / operating system). If there is not enough space (possibly due to too much memory fragmentation), it is possible to call the system function to increase the memory space of the program data segment, so that there is a chance to get enough memory and then return. Obviously, the heap is much less efficient than the stack.

From here we can see that heaps and stacks are compared due to the large number of New/delete is prone to large amounts of memory fragmentation , and is inefficient due to the lack of specialized system support, and the cost of memory applications becomes more expensive due to the possibility of triggering the conversion of user-state and kernel-mentality. So the stack is the most widely used in the program, even if the call of the function is done by the stack, the parameters in the function call, the return address, theEBP and the local variables are all stored in a stack. So, we recommend that you try to use stacks instead of heaps.

Although the stack has so many advantages, it is not so flexible compared to the heap, sometimes allocating a lot of memory space, or heap better.

Whether it is a heap or stack, you have to prevent the occurrence of cross-border phenomenon (unless you deliberately make it out of bounds), because the result of the cross-border is either a program crash, or destroy the program heap, stack structure, produce unexpected results , even when your program is running, no problem occurs, you still have to be careful , maybe when it will be blown off, then debug is quite difficult:)

C memory allocation method [reprint]

Related Article

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.