What is the difference between global variables and local variables in memory?

Source: Internet
Author: User

I. prerequisites-ProgramMemory Allocation

AC/C ++The memory occupied by compiled programs is divided into the following parts:

1Stack area (Stack)- Released automatically by the compiler Stores the function parameter values and local variable values. The operation method is similar to the stack in the data structure.

2, Heap area (Heap) - Usually assigned and released by programmers, If the programmer does not release the programOSReclaim . Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.

3, Global zone (static Zone )(Static)-The storage of global variables and static variables is stored in one area, and the initialized global variables and static variables are stored in one area, Uninitialized global variables and uninitialized static variables are in another adjacent area.-System release after the program ends

4, Text Constant Area -Constant strings are placed here. The program is released by the System

5, ProgramCodeZone-stores the binary code of the function body.

 

Ii. Example Program

This is written by a senior. It is very detailed.

// 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,P3Stack.

Static int C = 0;//Global (static) initialization Zone

P1 = (char *) malloc (10 );

P2 = (char *) malloc (20 );

//Allocated10And20The Byte area is in the heap area.

Strcpy (P1, "123456"); // 123456 \ 0In the constant area, the compiler mayP3Point"123456"Optimized to one 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.