Details about C/C ++ memory allocation knowledge instances

Source: Internet
Author: User
Tags constant

In C language, memory is divided into five areas:

Stack: used to store the function parameters and local variables in the function. Space allocated by the compiler is automatically released by the compiler after the function is executed.
Heap: used to store space allocated by dynamic allocation functions (such as malloc. It is manually assigned by the programmer and must be released by the programmer using free. If you forget to use free release, the allocated space will remain occupied, leading to memory leakage.
Global/static zone: used to store Global and static variables. When a program ends, it is released by the system, which is divided into the global initialization zone and the global uninitialized zone. The program exists throughout the runtime and is allocated and released by the compiler.
Text constant area: the constant string is placed here and released by the system at the end of the program. For example, if char * c = "123456", "123456" is a text constant, which is stored in the text constant area. It is also controlled by the compiler for allocation and release.
Code area: used to store the binary code of a program.

The following example shows how to allocate memory in the C program:

The code is as follows: Copy code
/* Example 1 main1.c
* Shows the memory allocation method in the C program.
*/
# Include <stdlib. h>
# Include <string. h>
 
Int a = 0; // global initialization zone
Char * p1; // not initialized globally
 
Int main ()
{
Int B; // stack
Char s [] = "abc"; // s in the stack, "abc" in the text constant area
Char * p2; // stack
Char * p3 = "123456"; // "123456" in the constant area, p3 in the stack
Static int c = 0; // Global Zone
P1 = (char *) malloc (10); // p1 is on the stack, and the allocated 10 bytes are on the heap
P2 = (char *) malloc (20); // p2 on the stack, 20 bytes allocated in the heap
Strcpy (p1, "123456"); // "123456" is placed in the constant area, and the compiler may be optimized to point to the same area as p3.
Return 0;
}

 

The code is as follows: Copy code
/* Example 2 main2.c
* Shows the memory allocation in C language.
*/
 
# Include <stdio. h>
 
// Returns the char pointer.
Char * f ()
{
// The s array is stored on the stack.
Char s [4] = {'1', '2', '3', '0 '};
Return s; // return the address of the s array, but the s array is released after the program runs.
}
 
Int main ()
{
Char * s;
S = f ();
Printf ("% s", s); // Print out garbled characters. Because s points to the address, there is no data
Return 0;
}




Five memory partitions in C ++:

In C ++, memory is divided into five areas: Heap, stack, free storage, Global/static storage, and constant storage.
Stack is the storage area for variables that are automatically allocated by the compiler when necessary and clear when not needed. The variables are usually local variables and function parameters.
Heap is the memory blocks allocated by new. Their release compilers are not controlled and controlled by our applications. Generally, a new compiler corresponds to a delete. If the programmer does not release the program, the operating system will automatically recycle it after the program is completed.
The free storage zone is the memory blocks allocated by malloc and so on. It is very similar to the heap, but it uses free to end its own life.
In the Global/static storage area, global variables and static variables are allocated to the same memory. In the previous C language, global variables were divided into initialized and uninitialized ones, in C ++, there is no such distinction. They share the same memory zone.
Constant storage area, which is a special storage area. It stores constants and cannot be modified (of course, you can modify them by improper means, and there are many methods)

Advanced Programming in Unix environment (famous APUE:
C program memory layout: Text, Data, BSS, Stack, Heap.
Text is the code segment of the program.
Data is a global and static Data variable initialized in the program.
BSS is a non-initialized global and static data variable in the program. Even if the global and static data variables are initialized to 0, they still belong to the BSS segment. (Uninitialized data segment)
Stack is a local variable in the program, increasing from High address to low address.
Heap is the memory dynamically allocated by calling malloc, increasing from low address to High address.

According to others' opinions on the Internet, combined with their own tests, the conclusion is as follows:

1. Initialized global variables and static variables are stored in the data segment.
2. Uninitialized global variables and static variables are stored in the BSS segment.
3. The local variables declared in the function are stored in the stack segment (stack), and function call information is also stored in the stack.
4. The global variables modified by const are saved in the text segment, and the local variables modified by const are saved in the stack segment.
5. String constants are stored in text segments.

Run the size command: size test. out (test. out is the executable file after compilation and connection) to view the size of the text, data, and bss segments.

Stack and stack discussion:
Management method:
Resources in the heap are controlled by programmers (memory leak is easily generated ).
Stack resources are automatically managed by the compiler without manual control.

System response:
For heap, you should know that the system has a linked list that records the idle memory address. When the system receives a program application, it traverses the linked list to find the first heap node with a space greater than the requested space, delete the node in the idle node linked list and allocate the node space to the program (most systems will record the size of the allocation at the first address of the memory space, in this way, delete can correctly release the memory space, and the system will re-place the excess parts into the idle linked list ).
For a stack, the system provides the program with memory as long as the remaining space of the stack exceeds the Applied Space. Otherwise, an exception is reported, prompting Stack Overflow.

Space size:
The heap size is limited by the effective virtual memory in computer systems (32 bit systems are 4 GB in theory). Therefore, the heap space is flexible and large.
The stack size is predetermined by the operating system/compiler.

Fragmentation problem:
For heaps, frequent new/delete operations can cause a large number of fragments, reducing program efficiency.
For stacks, it is an advanced and post-output queue, with one-to-one access and no fragmentation.

Growth direction:
Heap up, to the high address direction growth.
Stack down, to the low address direction growth.

Allocation method:
Heap is dynamically allocated (no static heap allocation ).
The stack has static allocation and dynamic allocation. The static allocation is completed by the compiler (such as local variable allocation), and the dynamic allocation is allocated by the alloca function, but the resources dynamically allocated by the stack are released by the compiler, no need for programmers.

Allocation efficiency:
The heap is provided by the C/C ++ function library, and the mechanism is complex. Therefore, the heap efficiency is much lower than the stack efficiency.
Stack is a data structure provided by an extremely systematic system. Computers provide support for stacks at the underlying layer, allocate special registers to store Stack addresses, and stack operations have special commands.

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.