The difference between stack memory and heap memory

Source: Internet
Author: User


Summarize:
1 Stacks: Automatic allocation and deallocation of compilers, such as function parameters, local variables, temporary variables, etc.
2 Heap: Assign and release for members, apply by the programmer himself, release himself. Otherwise, a memory leak occurs. The heap content that is typically applied for using new.

In addition to these two parts, there is also a part:
3 Static Storage: There is a program compiled at the time of the allocation is good, this block exists throughout the operation of the program. It mainly stores static data, global data, and constants.

Turn from:
The difference between stack memory and heap memory (a part of a pen question) http://blog.csdn.net/richerg85/article/details/19175133


Written question: Please explain the difference between a stack memory and a heap memory, please analyze the following code to run if there is a problem, please correct if there is a problem.

char* getmemory (void)

{

Char p[] = "Hello World";

return p;

}

void Main (void)

{

char* str = getmemory ();

printf (str);

}

First question: The difference between stack memory and heap memory

Memory allocation of the program
Stack: There are compiler automatic allocation and release, storing function parameters, local variables, temporary variables, function return address and so on;

Heap: Typically there are programmers assigned and released, and if not manually released, may be automatically released by the operating system at the end of the program (? This may be for the Java-like recycling mechanism of the language, for the C + +, such a need to manually release the open heap of memory, a little careless will cause a memory leak.

2. Response of the system after application

Stack: As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, or will report the exception prompt stack overflow.

Heap: In a linked list that records the free memory address, look for a heap node that is larger than the requested space, and then delete the node from the list of free nodes and assign the space of that node to the program. Also, for most systems, the size of the sub-allocation space is recorded in the first address of the memory space, so that delete in the code can properly free up the memory space. The system will re-idle the redundant portion of the list.

3. Application Size Limit
Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small.
Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.
4. Allocation efficiency
Stack: Automatically allocated by the system, faster. But programmers can't control it.
Heap: Memory allocated by new, generally slower, and prone to memory fragmentation, but the most convenient to use. In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, not in the heap, nor in the stack is directly in the process's address space to keep a fast memory, although the most inconvenient to use. But it's fast and flexible.
5. Store Content

Stack: In the stack, the first stack is the address of the next instruction of the main function, and then the parameters of the function, in most compilers, the argument is from right to left into the stack, and then a local variable in the function. Note that static variables are not in the stack. The stack is just in the opposite order.

Heap: The size of the heap is usually stored in the head of the heap with a single byte, and the content is arranged by the programmer.


According to C + + memory management technology Insider, in C + +, memory is divided into 5 zones, each of which is a heap, stack, free survival Zone, global/static survival zone, and constant survival area.

A) stack: the memory is automatically allocated and freed by the compiler when needed. Typically used to store local variables and function parameters. (Local variables, function parameters, return addresses, etc. allocated for running functions are stored in the stack area). The stack operation allocation is built into the processor's instruction set, which is highly efficient, but allocates limited memory capacity.

b) Heap: Memory is allocated using new, and is freed using Delete or delete[]. Failure to properly release memory can result in a memory leak. But at the end of the program, it is automatically reclaimed by the operating system.

c) Free storage: Use malloc for allocation, and then use to reclaim. Similar to the heap.

d) Global/static storage: Global variables and static variables are allocated in the same piece of memory, C language is distinguished from initialization and uninitialized, C + + is no longer differentiated. (Global variables, static data, constants stored in the global data area)

e) constant storage: Stores constants and is not allowed to be modified.

Here, in some of the data is the definition of C + + memory allocation, programmable within the existence of basically divided into such a few parts: static storage, heap and stack area. They have different functions and different ways of using them.

A) static storage: Within the time the program is compiled, it has been allocated, and the entire running period of the program exists in this block. It mainly stores static data, global data, and constants.

b) Stack: When executing a function, the storage units of local variables within the function can be created on the stack and are automatically freed when the function is executed. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.

c) Heap area: Also known as dynamic memory allocation. The program uses malloc or new to request any size of memory at run time, and the programmer is responsible for freeing the memory with free or delete when appropriate. The lifetime of dynamic memory can be determined by us, and if we do not release the memory, the program will release the dynamic memory at the end. However, good programming habits are: If a dynamic memory is no longer used, it needs to be released, otherwise, we think there is a memory leak phenomenon.

\
Figure 3 Typical C + + memory region

Summary: C + + and C language memory allocation is different, but the overall consistency, will not affect the program analysis. In the case of C + +, whether it is 5 or 3, the division is inconsistent, and (c) d) E in 5) (Part A) is 3.

The following sections of code will give you a sense of suddenly understanding:
VOID Fn ()

{

int* p = new Int[5];

}

To see new, we should first think that we allocated a heap of memory, then the pointer p? It 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 determines the size of the memory allocated in the heap, then calls operator new to allocate memory, then returns the first address of the memory and puts it into the stack.

Note: In order to simply not release the memory, then how to release it? Is it deletep? NO, wrong, it should be delete [] p, which is telling the compiler: the deletion is an array.


Main.cpp
int a = 0; Global initialization Zone
Char *p1; Global uninitialized Zone
Main ()
{
int b; Stack
Char s[] = "ABC"; Stack
Char *p2; Stack
Char *p3 = "123456"; 123456\0 in the constant area, p3 on the stack.
static int c = 0; global (static) initialization zone
P1 = (char *) malloc (10);
P2 = (char *) malloc (20);
Areas that are allocated 10 and 20 bytes are in the heap area.
strcpy (P1, "123456"); 123456\0 is placed in a constant area, the compiler may optimize it to a place with the "123456" that P3 points to.
}

The difference between stack memory and heap memory

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.