The difference between heaps and stacks

Source: Internet
Author: User

Original: http://student.csdn.net/link.php?url=http://www.top-e.org%2Fjiaoshi%2Fhtml%2F427.html

Format and part of the content are modified slightly.

In the computer field, the stack is a concept that cannot be ignored, and the C language programs we write are basically used. But for many beginners, the stack is a very vague concept. Stacks: A data structure, a place to store when the program is running, which may be a lot of beginners ' understanding, because I used to think of it as a stack in assembly language. My side of some programming friends and in the Internet to see the number of friends there are many also do not know the stack, so I think it is necessary to share my views on the stack, have said the wrong place please friends, this will be a great help to learn from you.

Stacks and heaps of data structures

The stack is first known on the data structure, although we call it that, but the stack is actually two kinds of data structures: heap and stack.

Heaps and stacks are a data structure in which data items are ordered sequentially.

Stacks are like buckets or chests of data.

We start from the familiar stack, it is a kind of data structure with the last-first-out nature, that is, after the storage of the first take, the first storage after the take. It's like we're going to take out something that's under the box (put in an earlier object), and we'll first remove the object that's pressed on it (the relatively late object put in).

Heap like a tree upside down

And the heap is different, the heap is a sort of tree data structure, each node has a value. Usually what we call a heap of data structures is a two fork heap. The heap is characterized by the minimum (or maximum) value of the root node, and the two subtrees of the root node are also a heap. Because of this feature of the heap, commonly used to achieve the priority queue, heap access is arbitrary, it is like we in the library shelves to pick up books, although the book is placed in order, but we do not want to take any of the same as the stack, first remove all the previous books, bookshelf This mechanism is different from the box, we can directly take out the book

Stacks and heaps in memory allocation

However, I would like to say that the focus is not in this, I would say that the heap and stack is not a data structure of the heap and stack, the reason is to say that the data structure of the heap and stack is to the back I want to say the heap area and the stack area, please be sure to pay attention.

The following is the C language Program memory allocation in the heap and stack, here is necessary to the memory allocation also mention, we do not think of my wordy, in general, the program is stored in ROM or flash, the runtime needs to be copied into memory execution, memory will store different information, as shown in:

When the in-memory stack area is at a relatively high address, the stack address is increased downward in the direction of the address growth.

The stack is allocated a local variable space, and the heap area is the amount of memory space that is increased to allocate the programmer's request. In addition, static zones are allocated static variables, global variable space, read-only areas are assigned constants and program code space, and some other partitions.

Take a look at a classic example that is popular online:

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); Heap

P2 = (char *) malloc (20); Heap

}

0. Different application methods and recycling methods

I do not know if you have a little understanding, the first difference between heap and stack is the application method is different: Stack (English name is stack) is the system automatically allocated space, for example, we define a char A; the system automatically opens up space on the stack. The heap (the English name is heap) is the space that the programmer applies for, such as malloc (10), and 10 bytes of space to open. Since the space on the stack is automatically collected automatically, the life cycle of the data on the stack is only run in the function, it is released after running, and can no longer be accessed. The data on the heap can be accessed as long as the programmer does not free up space, but the drawback is that once you forget to release it will cause a memory leak. There are some other differences I think the friends on the net summed up a good here to repeat:

1. 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, otherwise it will report the exception prompt stack overflow.

Heap: The first thing you should know is that the operating system has a linked list that records the free memory address, and when the system receives the application, it iterates through the list, looking for the first heap that is larger than the requested space.

node, and then removes the node from the list of idle nodes and assigns the node's space to the program, and for most systems, the size of this allocation is recorded at the first address in the memory space, so that the DELETE statement in the code can properly free up the memory space. Also, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.

In other words, the heap will have to do some follow-up work after the application, which will lead to the question of application efficiency.

2. Comparison of application efficiency

According to No. 0点 and 1th.

Stack: Automatically allocated by the system, faster. But programmers can't control it.

Heap: Is the memory allocated by new, the general speed is slow, and prone to memory fragmentation, but the most convenient to use.

3. Restrictions on size of applications

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. Storage content in heaps and stacks

Because the size of the stack is limited, the use of sub-functions has physical meaning, not just logical meaning.

Stack: When the function is called, the first stack is the address of the next instruction (the next executable statement of the function call statement) after the function call in the main function, and then the parameters of the function, in most C compilers, the arguments are in the right-to-left stack, followed by the local variables in the function. Note that static variables are not in the stack.

When the function call is finished, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.

Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.

You can also refer to this question for storage content. This problem also involves the survival period of local variables.

5. Comparison of Access efficiency

Char s1[] = "AAAAAAAAAAAAAAA";

Char *s2 = "BBBBBBBBBBBBBBBBB";

The AAAAAAAAAAA is assigned at runtime and placed in the stack.

The BBBBBBBBBBB is determined at compile time, and is placed in the heap.

However, in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap).

Like what:

#include

void Main ()

{

char a = 1;

Char c[] = "1234567890";

Char *p = "1234567890";

A = c[1];

A = p[1];

Return

}

The corresponding assembly code

10:a = c[1];

00401067 8A 4D F1 mov cl,byte ptr [ebp-0fh]

0040106A 4D FC mov byte ptr [ebp-4],cl

11:a = p[1];

0040106D 8B-EC mov edx,dword ptr [ebp-14h]

00401070 8A mov al,byte ptr [edx+1]

00401073 FC mov byte ptr [ebp-4],al

A metaphor for the difference between heaps and stacks

The difference between heaps and stacks can be seen by referring to the analogy of a predecessor:

Use the stack like we go to a restaurant to eat, just order (send application), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.

The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom. Metaphor is very image, said very easy to understand, do not know whether you have a little harvest.

The difference between heaps and stacks

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.