On the memory of C language

Source: Internet
Author: User

The memory allocation problem of the operating system and the memory alignment problem are very important for stratigraphic programming, and the understanding of memory allocation directly affects the quality of the code, accuracy, efficiency, and the programmer's judgment on memory usage, overflow, and leakage. Memory alignment is often overlooked, and understanding the principles and methods of memory alignment helps programmers to determine access to illegal memory. The memory used by the general C + + program is divided into the following five types:
1. Stack: The system is automatically assigned, automatically created by the program, automatically released. Information such as function arguments, local variables, and return values exists
2. Heap area: Free to use, no predetermined size is required. How many cases require the programmer to manually apply, release. If not released, an operating system garbage collection mechanism is withdrawn after the program ends. For example, s = (char *) malloc (10),
3. Static zone/Global zone (Static): The storage area for global variables and static variables. Released by the system after the program is finished
4. Constant area: The area of memory used to hold constants
5. Code Area: Store Code
For example:
#include <stdio.h>
int quanju;/* global variable, global zone/static zone (Static) */
void Fun (int f_jubu); /* Program code Area */
int main (void)/**/
{
int m_jubu;/* stack (stack) */
static int m_jingtai;/*, global zone/static zone (Static) */
char *m_zifum,*m_zifuc = "Hello";/* The pointer itself is on the stack. Point to the string "Hello", located in the literal constant area */
void (*pfun) (int); /* Stacking Area (STACK) */
pfun=&fun;
M_zifum = (char *) malloc (sizeof (char) *10);/* Pointer content points to allocated space, in heap area (heap) */
Pfun (1);
printf ("&quanju:%x/n", &quanju);
printf ("&m_jubu:%x/n", &m_jubu);
printf ("&m_jingtai:%x/n", &m_jingtai);
printf ("M_zifuc:%x/n", M_ZIFUC);
printf ("&m_zifuc:%x/n", &AMP;M_ZIFUC);
printf ("M_zifum:%x/n", m_zifum);
printf ("&m_zifum:%x/n", &m_zifum);
printf ("Pfun:%x/n", pfun);
printf ("&pfun:%x/n", &pfun);
Getch ();
return 0;
}
void Fun (int f_jubu)
{
static int f_jingtai;
printf ("&f_jingtai:%x/n", &f_jingtai);
printf ("&f_jubu:%x/n", &f_jubu);/* Stack (stack), but m_jubu on different stacks in the main function */
}
Heap and Stack
1. How to Apply
Stack
Automatically assigned by the system. For example, declare a local variable in a function char C; The system automatically opens up space in the stack for C
Heap
Requires the programmer to manually apply and indicate the size in C, with the malloc function complete. such as P1 = (char *) malloc (10)
2. Response of the system after application
Stack
As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
Heap
Most operating systems have a linked list that records the free memory address, and when the system receives a request for a program, it iterates through the list, finds the heap node where the first space is larger than the requested space, and then removes the node from the list of idle nodes and assigns the node's space to the program, and for most systems, The size of this allocation is recorded at the first address in this memory space, so that the free function in the code can properly release the memory space. Also, because the size of the found heap node is not necessarily exactly equal to the size of the request, the system automatically re-places the extra part in the idle list
3. Restrictions on size of applications
Stack
Under Windows, the stack is the data structure that extends to the low address, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small
Heap
A heap is a data structure that extends to a high address and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and larger
4. Comparison of application efficiency
Stack
Automatically assigned by the system, faster. is beyond the control of the programmer.
Heap
Manually allocated memory by programmers, generally slower, and prone to memory fragmentation, but the most convenient to use
5. Storage content in heaps and stacks
Stack
In a function call, the first stack is the address of the next executable statement in the function call statement, and then the parameters of the function, in most C compilers, the arguments are left-to-right and then the local variables in the function. Note that static variables are not in the stack. When the function call is finished, the local variable is first out of the stack, then the argument, and the last stack pointer points to the first saved address, the next instruction in the function, and the program continues to run.
Heap
It is generally the size of the heap in the head of the heap that is stored in a single byte. The concrete contents of the heap are arranged by the programmer
Memory alignment Issues
The memory space in modern computers is divided by byte, theoretically it seems that access to any type of variable can start from any address, but the reality is that when accessing a particular variable, it is often accessed at a specific memory address, which requires all types of data to be spatially arranged according to certain rules, Instead of sequentially one by one emissions, that's the alignment. Normally, when we write a program, we don't need to consider alignment issues. The compiler chooses the alignment strategy for the target platform for us. Of course, we can also notify the compiler to pass the precompiled instructions and change the alignment of the specified data.
1. Reasons for Memory alignment
The processing of storage space varies greatly with each hardware platform. Some platforms can only access certain types of data from certain specific addresses. Other platforms may not, but the most common is the loss of access efficiency if data storage is not aligned as required for its platform. For example, some platforms each read from the even address, if an int (assuming 32-bit) if it is stored at the beginning of the even address, then a reading period can be read out, and if stored in the location of the odd address, it may require 2 read cycles, and two read the results of the high and low Byte is pieced together to get the int data. Obviously, the reading efficiency is much lower. It's also a game of space and time.
2. Correctly handle byte alignment
For a standard data type, its address is as long as it is an integer multiple of its length, and non-standard data types are aligned according to the following principle:
A. Arrays: aligned According to the basic data type, and the first one is aligned with the nature of the back.
B. Union: Aligns by the data type that contains the largest length
C. struct: Each data type in the struct is aligned
Starting from the first address of the struct, each member is searched for the first address x that satisfies the condition, the condition is x% N = 0, and the length of the entire structure must be the smallest integer multiple of the largest value in the alignment parameter used by each member, not enough to fill the empty bytes
3. Alignment rules
Compilers on each particular platform have their own default "alignment factor" (also known as the number of Zimo). Programmers can change this factor by precompiling the command #pragma pack (n), where n is the "alignment factor" you want to specify. The alignment rules are as follows:
A. Data member alignment rules: data members of a struct (struct) (or union), where the first data member is placed at offset 0, and subsequent alignment of each data member according to the numeric value (or default value) specified by the #pragma pack and the length of the data member type, The relatively small one is carried out. Start looking for addresses that can be divisible by the current alignment value in the last aligned place
B. The overall alignment rules of the structure (or union): After the data members have completed their respective alignments, the structure (or union) itself is aligned. The main embodiment is, after the last element is aligned, whether or not to fill the empty bytes, if filled, how much to fill. Align the numeric value (or default) that will be specified by #pragma pack and the structure (or union) of the maximum data member type length, which is smaller than the
C. The combination of 1, 2 can be inferred: when the n value of the #pragma pack equals or exceeds the length of all data member types, the size of this n value will have no effect
4. There are four concept values:
1. The alignment value of the data type itself: is the self-aligning value of the underlying data type that was confessed above.
2. Specify the alignment value: The specified alignment value when #pragma pack (value) is values.
3. The self-aligning value of a struct or class: The value that is the largest of its members in its own alignment value.
4. Valid alignment values for data members, structs, and classes: their own alignment values and the smaller values in the specified alignment values.
Because of the different platforms and compilers, my GCC version 4.1.2 20080704 (Red Hat 4.1.2-52) is used to discuss how the compiler aligns the members of the struct data structure. For example:
1.struct A {
int A;
Char b;
Short C;
}; #结构体A中包含了4字节长度的int一个, a 1-byte length of char one and a 2-byte length of short data. So the space used for a should be 7 bytes. However, because the compiler wants to align data members spatially, use the sizeof (Strcut A) value of 8.
2.struct B {
Char b;
int A;
Short C;
};
#假设B从地址空间0x0000开始排放. In this example, the specified alignment value is not defined, and in the author's environment, the value defaults to 4. The first member variable B has a self-aligning value of 1, which is smaller than the specified or default alignment value of 4, so its valid alignment value is 1, so its storage address 0x0000 conforms to 0x0000%1=0. The second member variable A has its own alignment value of 4, so the valid alignment value is also 4, so it can only be stored in the starting address of 0x0004 to 0x0007 four contiguous byte space, review 0x0004%4=0, and immediately close to the first variable. The third variable, C, has its own alignment value of 2, so the valid alignment value is also 2, which can be stored in the two byte space of 0x0008 to 0x0009, conforming to 0x0008%2=0. So everything from 0x0000 to 0x0009 is stored in B content. Then look at the data structure B's own alignment value for its variable maximum alignment value (here is B) so is 4, so the structure of the effective alignment value is also 4. 0x0009 to 0x0000=10 bytes, (10+2)%4=0 according to the requirements of the structural rounding. So 0x0000a to 0x000b is also occupied by struct B. So B a total of 12 bytes from 0x0000 to 0x000b, sizeof (struct B) =12
3. #pragma pack (2)/* Specify to align by 2 bytes */
struct C {
Char b;
int A;
Short C;
};
#pragma pack ()/* To cancel the specified alignment, restore the default alignment */
#们使用预编译指令 #pragma pack (value) to tell the compiler. The first variable B has its own alignment value of 1, the specified alignment value is 2, so its valid alignment value is 1, assuming that C starts with 0x0000, then B is stored in 0x0000, conforms to 0x0000%1= 0, the second variable has its own alignment value of 4, and the alignment value is 2, so the valid alignment value is 2. So the order is stored in 0x0002, 0x0003, 0x0004, 0x0005 four consecutive bytes, in accordance with 0x0002%2=0. The third variable, C, has its own alignment value of 2, so the valid alignment value is 2, which is stored sequentially
In 0x0006, 0x0007, in accordance with 0x0006%2=0. So from 0x0000 to 0x00007 a total of eight bytes is stored in the C variable. and C has its own alignment value of 4, so the valid alignment value for C is 2. And 8%2=0,c only takes up eight bytes of 0x0000 to 0x0007. So sizeof (struct C) =8
4. #pragma pack (1)/* Specify to align by 1 bytes */
struct D {
Char b;
int A;
Short C;
};
#pragma pack ()/* To cancel the specified alignment, restore the default alignment */
The #sizeof (struct C) value is 7
5.union e{
int a[5];
Char b;
Double C;
}; #我想的是union中变量共用内存, the longest should prevail, that is 20. The default memory alignment for each variable in E, which must be aligned with the longest double 8 bytes, should be sizeof (e) =24
Attention:
1. The array alignment values are: min (array element type, specify alignment length). But the elements in the array are stored continuously, and are stored in the actual length of the array.
such as Char T[9], the alignment length is 1, the actual occupation of a continuous 9byte. It then determines how many bytes to fill before the next element, based on the alignment length of the next element.
2. Nested structure assumptions
struct A
{
......
struct b b;
......
};
The alignment length for the b struct in A is: min (the alignment length of the structure B, the specified alignment length). The alignment length of the B structure is: the alignment length in the overall alignment rules for the 2 structure above.

On the memory of C language

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.