C + +: Five memory allocation areas

Source: Internet
Author: User

The area of memory occupied by a program compiled by C + + is generally divided into the following 5 parts: (1) Stack: The compiler automatically allocates and releases the parameters, local variables, etc. that are used to store functions. It operates in a manner similar to a stack in a data structure. (2) Heap: typically assigned and released by programmers (via Malloc/free, New/delete), if the programmer is not released, the program is reclaimed by the operating system at the end. It is different from the heap in the data structure and is distributed in a similar way to a linked list. (3) Global/static zones: The storage of global variables and static variables is placed in a block, initialized global variables and initialized static variables in an area, uninitialized global variables and uninitialized static variables in another adjacent area, after the end of the program is recycled by the operating system. (4) Literal constant area: store constant value, normal string, etc., do not allow modification, after the end of the program by the operating system recovery. (5) Program code area: the binary code that holds the function body.

Example:

#include <stdlib.h>
#include <string.h>

int a = 0; Global initialization Zone
char* P1; Global uninitialized Zone

int main () {
int A; Stack area
Char s[] = "ABC"; Stack area
char* P2; Stack area
char* p3 = "123456"; 123456\0 in the constant area, p3 in the stack area
static int c = 0; Global/Static initialization zone
P1 = (char*) malloc (10);
P2 = (char*) malloc (20); 10 and 20 bytes allocated in the heap area
strcpy (P1, "123456"); 123456\0 is placed in a constant area, the compiler might optimize it to a place with the "123456" that P3 points to
return 0;
}

C + +: Five memory allocation areas

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.