C program memory management and Memory Management

Source: Internet
Author: User

C program memory management and Memory Management

C program memory management

If you are familiar with the Java language, you must know that memory management in Java is completed by virtual machines. This is not the case in C/C ++. Programmers need to allocate and recycle memory space on their own. This article records the storage structure of C Programs in the memory, the common storage types of C variables and functions, and the distribution and recovery of memory. The following C programs use the GCC 4.4.7 compiler version.

Starting with a C program

File structure

I am not familiar with the following Hello. c program.

#include<stdio.h>int main(void){        printf("Hello World\n");        return 0;}

Next, compile it with gcc, run the executable file, and view the storage structure of the executable file.


It can be seen that when the executable file Hello is stored (when the memory is not transferred), it is divided into three parts: the code area (text), the data area (data) and the uninitialized data area (bss. In the other three fields, dec indicates the decimal sum, hex indicates the hexadecimal sum, and filename indicates the file name. The specific description of each section is as follows:

(1)Code segment (text segment): The machine command that stores CPU execution. Generally, the code area can be shared (that is, other execution programs can call it ). The Code area is usually read-only to prevent the program from accidentally modifying its commands.Allocate memory for constant data during compilation in the Code Area. Commands in the code area include operation codes and operation objects (or object address reference ). If it is an immediate number, it is directly included in the Code; if it is local data, it will be allocated in the stack space during the runtime, and then the address that references the data; for the bss and data areas, the data address is also referenced in the code.

(2)Initialized data segment/data segment), Or data segment for short: This region contains the global variables explicitly initialized in the program, static variables that have been initialized (including Global static variables and local static variables ). Note that,The variables and string constants declared by const are allocated memory in the code segment.. This is similar to the concept of data segments in assembly languages.

(3)Uninitialized data zone bss (Block Started By Symbol): Uninitialized global variables and static variables are stored.Data in the bss region will be initialized to 0 by the kernel or NULL pointer before the program is executed)This is different from the variables in the stack. If the variables (local variables) in the stack are used without initialization, the system will randomly allocate a value to it, which is insecure.

The above are the Storage Structure Analysis of executable files. In fact, the memory structure during runtime is very similar to this, except that the heap memory and stack memory areas are added, which will be analyzed later. The following is an example.

Take the Hello. c program as an example.


We are at Hello. c adds a code to define a constant I. Through analysis and comparison, we can find that the text area size of the code segment has increased by 4 bytes (one int type occupies 4 bytes ), other regions remain unchanged. We can see that constants are allocated in the code segment.

On the basis of the above, add a sentence, define a global variable a, and assign it a value of 2 to observe the changes in each region.

It is found through comparison that only the size of the data segment is increased by four bytes, and it also proves that the initialized global variables are allocated in the Data zone. The same is true for static variables.

On the basis of the above, we define a global variable B, but this one should not be assigned a value, observe the changes in various regions


It can be found that this time only four bytes are added to the bss region, and the uninitialized global variables are allocated to the bss region. The same is true for uninitialized static variables.

Process Structure

A program is executed as one or more processes. In fact, the data structure of the Process kernel is similar to the storage structure of the above files, mainly because the heap memory and stack memory areas are more. Shows the main layout.


Each part is described as follows:

(1) text segment): The code segment of the preceding executable file is loaded, and its location in the memory is completed by the loader.

(2) Global initialization Data zone/static Data zone (Data Segment): Load the data segment of the preceding executable file, which is located behind the executable code segment and may be unconnected. At the beginning of the program running, I applied for a space for the data segment and released the space when the program exited. Its life cycle is the entire program running period.

(3) Data zone not initialized (BSS ):The load is the BSS segment of the preceding executable file, which is located after the data segment and can be separated. Its lifecycle is the same as that of the Data Segment.

(4) Stack): The Compiler automatically allocates the release to store the parameter values, return values, and local variables of the function. The stack is dynamically allocated and released when the program is running. The stack zone is placed after the BSS and is scaled up to a limited number.

(5) Heap): Used for dynamic memory allocation. Located behind the stack area, it is limited downward expansion. Generally, programmers are allocated and released. If the program is not released, the OS is responsible for the collection at the end of the program.


(To be continued)







C/C ++ Memory Management Problems

There are three memory allocation methods:
(1) distribution from the static storage area. The program has been allocated when it is compiled, and the program exists throughout the entire runtime. For example, global variables and static variables.
(2) create a stack. When a function is executed, the storage units of local variables in the function can be created on the stack. When the function is executed, these storage units are automatically released. Stack memory allocation computation is built into the processor's instruction set, which is highly efficient, but the memory capacity allocated is limited.
(3) allocate from the stack, also known as dynamic memory allocation. When the program runs, it uses malloc or new to apply for any amount of memory. The programmer is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory is determined by us. It is very flexible to use, but the problem is also the most. Only Memory allocated on the heap needs to be released (and must be). Otherwise, memory leakage will occur.

For example:
Char a = 3;
Char func (char B)
{
Char c = 5;
Char * d = new char [1];
Delete [] d; d = 0;
Return c;
}

Here, a is a global variable, and 1 byte is allocated to it from the static storage area; B, c, and d are local variables; B and c are allocated on the stack; d is allocated on the heap. D memory needs to be released before the program exits.
Reference: dev.yesky.com/#/2380608.shtml

Hope to answer the question of Windows application memory management ??????

The above two figures are clear about the memory management of the operating system. However, it should also be said that the size of a program's disk is not proportional to the memory occupied during its operation. Generally, the more commands a program contains, the more space it occupies on the disk, but the memory it occupies is not necessarily large. For example, you can use a few lines of code to consume your memory, double a [10000000] [1000000] [100000]. Of course this is not feasible, just an easy-to-understand example. Another example is to use memory graphics to make a large bitmap. In the opposite example, a lot of code may occupy a small amount of memory, such as applying for memory repeatedly, deleting it, and then applying for new class ()
Delete p;
And so on.
No matter how much code you execute, the memory usage will not increase, but the command will increase significantly.

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.