Heap, stack, queue in C language

Source: Internet
Author: User

Heap, stack, and queue in C language:

1. Heap and Stack

(1) heap and stack of data structures

Stacks are two kinds of data structures.

Stack (stack like a bucket or a box of data): is a data structure with a last-in-first-out nature, that is, after the storage of the first fetch, the first storage after the fetch. This is like removing the object that is placed under the box (the older object is placed), first remove the objects that are pressed on it (the later objects are placed).

Heap (heap like an upside-down tree): is a sort of tree-shaped data structure, each node has a value. Commonly referred to as a heap of data structures, refers to 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 in the library shelves to pick up books, although the book is placed in order, but want to take any one without the same as the stack, first out of all the books, bookshelf This mechanism differs from the box, we can directly take out the book we want.

(2) heap and stack in memory allocation

C Language Program memory allocation in the heap and stack. C Language program compiled after the formation of a compiled, connected to form a binary image file by the stack, heap, data segment (composed of three parts: read-only data segment, has initialized the read and write data segments, uninitialized data segment, BBS) and code snippets, as shown in:



Stack area: At a relatively high address, in the direction of the growth of the address, the stack address is growing downward;

Heap area: is an upward-growing memory space used to allocate programmer requests.

An example:

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
}


The difference between heap and stack:

(a) different application methods and recycling methods
1) stack (SATCK): Automatically assigned by the system. For example, declare a local variable int b in the function, and the system automatically opens up space for B in the stack.
2) Heap: Requires the programmer to apply (call Malloc,realloc,calloc) and specify the size and release by the programmer. Easy to produce memory leak.
For example: char *p;

p = (char *) malloc (sizeof (char));
However, p itself is in the stack.

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.

(b) Response of the system after application

1) Stack: As long as the stack of space is larger than the requested space, the system will provide memory for the program, or will report the exception hint stack overflow.
2) Heap: First of all should know that the operating system has a record of the free memory address of the list, but the system receives the application of the program, it will traverse the list, the first space is larger than the requested space of the heap node, and then delete the node from the free list, and the node's space allocated to the program, in addition, The size of this allocation is recorded at the first address in this memory space, so that the free statement in the code can properly release the memory space. In addition, the size of the found heap node is not necessarily exactly equal to the size of the request, and the system automatically re-places the extra portion into the idle list.
Note: For the heap, frequent new/delete is bound to cause memory space discontinuity, resulting in a large number of fragments, so that program efficiency is reduced. For the stack, there is no problem.

The heap will have to do some follow-up work after the application, which will lead to the problem of application efficiency.

(c) Efficiency of application
1) The stack is automatically assigned by the system and is fast. But programmers are beyond control.
2) heap is the memory allocated by malloc, the general speed is relatively slow, and easy to produce fragments, but the most convenient to use.

(d Application size limit
1) 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 the windows , the size of the stack is 2M (also some say 1M, in short, is a compile-time determined constant), If the requested space exceeds the remaining space on the stack, overflow will be prompted. Therefore, the space available from the stack is small.  
2) heap: A heap is a data structure that extends to high addresses 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.

< Span style= "font-size:18px" > (e) storage contents in heap and stack
1) stack: When a 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.  
2) heap: Typically, the heap's size is stored in a single byte on the head. The concrete contents of the heap are arranged by programmers.

< Span style= "font-size:18px" > (f) Access efficiency
1) heap: char *s1= "Hellow Tigerjibo"; is in the compilation is OK;
2) Stack: char s1[]= "Hellow Tigerjibo"; is assigned at run time; it is faster to use an array than a pointer, and the pointer needs to be brokered in the underlying assembly with the EDX register, and the array is read on the stack.
Add:
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 C + + function library, its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for available enough space, if there is not enough space (possibly due to too much memory fragmentation), It is possible to invoke the system function to increase the memory space of the program data segment, so that there is a chance to divide the memory in sufficient size and then return. Obviously, the heap is much less efficient than the stack.

(g) Distribution modalities:
1) The heap is dynamically allocated and there is no statically allocated heap.
2) Stacks are allocated in two ways: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. Dynamic allocations are allocated by the ALLOCA function, but the dynamic allocation of stacks is different from the heap. Its dynamic allocation is released by the compiler without the need for manual implementation.


Finally, a metaphor for the image of stacks and heaps:

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, the benefits are fast, but less freedom.
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.




2. Stacks and queues (data structures)

(1) Stack

Basic concepts

(a) Definition: a linear table that restricts insert and delete operations only at the fixed end.
Features: LIFO.
(b) One end of the allowed insert and delete operations is called the top of the stack, and the other end is called the bottom of the stack.
Function: The conversion from the input data sequence to some output data series can be completed.


Stack abstract data type
Data collection:
{a0,a1,..., an-1}, the AI has a data type of datatype.
Operation Collection:
(a) Stackinitiate (s): Initialize stack S
(b) Stacknotempty (s): Stack S non-null No
(c) Stackpush (S, X): Into the stack
(d) Stackpop (S, D): Out of stack
(e) Stacktop (S, D): Fetching stack Top data elements


Stack type

(a) Sequential stacks

Sequential stacks: stacks of sequential storage structures.
Storage structure of sequential stacks: data elements from the bottom of the stack to the top of the stack are stored sequentially using a contiguous set of storage units.


Data:

typedef struct
{

Datatypestack[maxstacksize];
int top;
}seqstack;

(b) Chained stacks

Chained stacks: A stack of chained storage structures.
The storage structure of a chained stack: It is a chain stack structure that takes the head pointer as the top of the stack, inserts or deletes at the head pointer, and leads the node:

Each node in the chain is comprised of two fields: the data domain and the next field.

The node structure is defined as follows.
typedef struct SNODE
{
DataType data;
struct Snode *next;
} Lsnode;

The advantage of using the chain stack storage method is that when the number of elements in the stack changes large, the exact number is difficult to determine, the chain stack is more convenient than the sequential stack.


(2) Queue

Basic concepts
Definition: A linear table (team header) that deletes operations at the other end of the table, only at one end of the table (tail of the queue). A queue is as follows:


Queue abstract Data type

Data collection: {a0,a1,..., the An-1},ai data type is datatype.
Operation Collection:
(a) initialization of queueinitiate (Q)
(b) non-null no Queuenotempty (Q)
(c) into the queue queueappend (q,x)
(d) out of queue Queuedelete (Q,D)
(e) take the team head data element Queueget (Q, D)


Queue type:

(a) Sequential queue

Sequential queue: A queue of sequential storage structures.

Storage structure for sequential queues: the sequential queue with 6 storage spaces is dynamic as follows.


False overflow problem for sequential queues: situations where there is storage space but cannot be queued because of multiple inbound and outbound queue operations.

There are four ways to solve the problem:
1) Adopt sequential cycle queue;
2) Set the maximum number of elements in the sequential queue (the worst method) according to the maximum possible number of incoming operations;
3) Modify the algorithm of the team, so that the remaining data elements in the queue are moved to the team head direction after each outbound queue;
4) Modify the queue algorithm, increase the judging condition, when the false overflow, the data elements in the queues to the enemy, and then the party completed the operation.


(b) Sequential loop queue

Rationale: The storage space used by the sequential queue is constructed into a logically connected circular queue. When rear and front reach MaxQueueSize-1, a position is automatically reached 0.


Queue empty and team full judgment questions for Sequential loop queues:
In the sequential loop queue, the team empty feature is Front=rear, the team full time will also be front=rear, the verdict condition will appear two semantics, the solution has three:
1) Use a counter to record the number of elements in the queue (that is, queue length);
Team full: count>0 && Rear==front
Team Empty: Count==0
2) Set the mark: 0 when the team is out, the queue time is 1, it can identify the current front=rear belongs to what situation;
Team full: Tag==1 && Rear==front
Team empty: tag==0 && Rear==front
3) Use less than one storage unit
Team full: front= (rear+1)%maxqueuesize
Team Empty: Rear==front


The structure of the sequential loop queue is defined as follows:
typedef struct
{
DataType Queue[maxqueuesize];
int rear;
int front;
int count;
} Seqcqueue;


(c) Chain-queue

Chained queues: A queue of chained storage structures.
The storage structure of a chained queue: The team head pointer of a chained queue points to the current team head node of the queue; the tail pointer refers to the current team tail node in the queue. The structure of a chain queue that does not lead the node.


The structure of a node can be defined as follows:
typedef struct QNODE
{
Datatypedata;
struct Qnode*next;
}lqnode;
The structure type of the team head pointer front and the tail pointer rear:
typedef struct
{
Lqnode *front;
Lqnode *rear;
}lqueue;


(d) Priority queue

Priority queue: A queue with a priority level.
Sequential priority queue: The priority queue that stores the structure in order.
The primary difference between the priority queue and the general queue is that the out-of-queue operation of the priority queue does not take the team header elements out of the queue, but instead queues the highest-priority elements in the queue.


Its data element is defined as the following structure:
struct DataType
{
Elemtype elem;//Data Element
int priority; Priority level
};
Note: Sequential priority queue implementations other than queue operations are implemented in the same way as the sequential queue operations discussed before.

Heap, stack, queue in C language

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.