The difference between heap and stack

Source: Internet
Author: User
Tags constant data structures

Stack

In the computer field, the stack is a concept that can not be ignored, but many people even the computer professional people do not have a clear stack is actually two data structures.

Points:

Heap: Random in order

Stack: Advanced back out

The difference between heap and stack

First, the preparation of knowledge-Program memory allocation

The memory used by a program compiled by C + + is divided into the following sections

1, stack area (stack)-by the compiler automatically assigned to release, store the function of the parameter values, local variables and other values. The operation is similar to the stack in the data structure.

2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the program at the end may be reclaimed by the OS. Note that it is different from the heap in the data structure, the distribution is similar to the list, hehe.

3, Global area (static)--------------------------------------------------------------- -System release after the program is finished

4, literal constant area-the constant string is here. Released by system after program is finished

5, program code area-the binary code that holds the function body.

Second, the example procedure

This is written by a predecessor, very detailed

//main.cpp
int a = 0; 全局初始化区
char *p1; 全局未初始化区
main()
{
int b; 栈
char s[] = "abc"; 栈
char *p2; 栈
char *p3 = "123456"; 123456\0在常量区,p3在栈上。
static int c =0; 全局(静态)初始化区
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, and the compiler may optimize it with the "123456" that the P3 points to as a place.

}

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.