C language Variable declaration memory allocation

Source: Internet
Author: User
Tags stack pop

The memory used by a program compiled by C + + is divided into the following sections

1. Stack (stack)-the program is automatically assigned by the compiler when it is run, storing the parameter value of the function, the value of the local variable, etc. It operates in a manner similar to a stack in a data structure. Automatically released by the compiler at the end of the program.

2. Heap area-open another storage area in memory. Usually released by the programmer, if the programmer does not release, the program ends may be recycled by the OS. Note that it is not the same as the heap in the data structure, the distribution is similar to the list, hehe.

3. Global zone (static zone)-the compiler allocates memory at compile time. The storage of global variables and static variables is placed in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another contiguous area. -released by the system after the program is finished

4, literal constant area-the constant string is put here. Released by the system after the program is finished

5. Program code area-binary code that holds the function body.

Example Program

It was written by a predecessor, 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, p3 on the stack.

static int c = 0;//global (Static) initialization area

P1 = (char *) malloc (10);

P2 = (char *) malloc (20);

Areas that are allocated 10 and 20 bytes are in the heap area.

strcpy (P1, "123456"); 123456\0 is placed in a constant area, the compiler may optimize it to a place with the "123456" that P3 points to.

}

===============

How to allocate memory in C language programs

1. How to allocate memory
There are three ways to allocate memory:
[1] Allocated from a static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables, static variables.
[2] created on the stack. When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.
[3] Allocated from the heap, also known as dynamic memory allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by the programmer and is very flexible to use, but if space is allocated on the heap, it is the responsibility to reclaim it, otherwise the running program will have a memory leak, and frequently allocating and releasing different sizes of heap space will result in heap fragments.
2. Memory space of the program
A program assigns the operating system to a block of memory that it runs into 4 regions, as shown in.
The memory used by a program compiled by C + + is divided into the following sections,
1. Stack (stack)-Automatically allocated by the compiler to release, stored as a function to run the allocation of local variables, function parameters, return data, return address and so on. It operates in a manner similar to a stack in a data structure.
2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the end of the program may be recycled by the OS. The allocation method is similar to a linked list.
3. Global zone (static zone)-holds global variables, static data, constants. Released by the system after the program is finished.
4, literal constant area-the constant string is put here. Released by the system after the program is finished.
5. Program code area-binary code that holds the function body (class member functions and global functions).
Here is an example program,
int a = 0; Global initialization Zone
Char *p1; Global uninitialized Zone
int main () {
int b; Stack
Char s[] = "ABC"; Stack
Char *p2; Stack
Char *p3 = "123456"; 123456 in the constant area, p3 on the stack.
static int c =0;//Global (static) initialization zone
P1 = new CHAR[10];
P2 = new CHAR[20];
The area that is allocated and bytes is in the heap area.
strcpy (P1, "123456"); 123456 in the constant area, the compiler might optimize it to a place with the "123456" that P3 points to.
}
3. Heap vs. Stack comparison
3.1 How to apply
Stack: Automatically assigned by the system. For example, declare a local variable int b in the function; The system automatically opens up space for B in the stack.
Heap: Requires the programmer to apply himself and indicate the size of the malloc function in C, which is the new operator in C + +.
such as P1 = (char *) malloc (10); P1 = new CHAR[10];
such as P2 = (char *) malloc (10); P2 = new CHAR[20];
But note that P1, p2 itself is in the stack.
3.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: First of all should know that the operating system has a record of the free memory address of the list, when the system receives the application of the program, it will traverse the list, look for the first space is larger than the requested space of the heap node, and then delete the node from the list of idle nodes, and the node's space allocated to the program.
For most systems, the size of this allocation is recorded at the first address in the memory space, so that the DELETE statement in the code can properly free up the memory space.
Because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.
3.3 Application Size Limits
Stack: Under Windows, the stack is the data structure to the low address extension, 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 relatively large.
3.4 Comparison of application efficiency
The stack is automatically assigned by the system and is faster. But programmers can't control it.
Heap is the memory allocated by new, the general speed is relatively slow, and prone to memory fragmentation, but the most convenient to use.
In addition, under Windows, the best way is to use VirtualAlloc to allocate memory, he is not in the heap, not the stack, but directly in the process of the address space to retain a fast memory, although the most inconvenient to use. But the speed is fast, also the most flexible.
3.5 Storage contents in stacks and stacks
Stack: In a function call, the first stack is the address of the next instruction in the main function (the next executable statement of 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 parameter, and the last stack pointer points to the first saved address, which is the next instruction in the main function, and the program continues to run from that point.
Heap: The size of a heap is typically stored in a heap at the head of a pile. The concrete contents of the heap are arranged by programmers.
3.6 Comparison of Access efficiency
Char s1[] = "a";
char *s2 = "B";
A is assigned at run time, while B is determined at compile time, but in subsequent accesses, the array on the stack is faster than the string that the pointer points to (for example, a heap). Like what:
int main () {
char a = 1;
Char c[] = "1234567890";
Char *p = "1234567890";
A = c[1];
A = p[1];
return 0;
}
The corresponding assembly code
10:a = c[1];
00401067 8A 4D F1 mov cl,byte ptr [ebp-0fh]
0040106A 4D FC mov byte ptr [ebp-4],cl
11:a = p[1];
0040106D 8B-EC mov edx,dword ptr [ebp-14h]
00401070 8A mov al,byte ptr [edx+1]
00401073 FC mov byte ptr [ebp-4],al
The first reads the elements in the string directly into the register CL, while the second one reads the pointer values into edx and then reads the characters according to EdX, which is obviously slow.

3.7 Summary
The main differences between heaps and stacks are by the following points:
1, different management methods;
2, the space size is different;
3, can produce different fragments;
4, the growth direction is different;
5, the distribution method is different;
6, the allocation efficiency is different;
Management mode: For the stack, is automatically managed by the compiler, without our manual control, for the heap, the release of work by the programmer control, easy to produce memory leak.
Space size: Generally speaking, in 32-bit system, heap memory can reach 4G space, from this point of view heap memory is almost no limit. But for the stack, generally there is a certain amount of space, for example, under the VC6, the default stack space is 1M. Of course, this value can be modified.
Fragmentation problem: For the heap, frequent new/delete is bound to cause memory space discontinuity, resulting in a large number of fragments, so that program efficiency is reduced. For the stack, there will be no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there is never a memory block from the middle of the stack pop, before he pops up, in the back of his upper stack content has been ejected, detailed reference data structure can be referenced.
Growth direction: For the heap, the direction of growth is upward, that is, to the memory address of the direction of increase, for the stack, its growth direction is downward, is to reduce the memory address direction of growth.
Allocation method: The heap is dynamically allocated and there are no statically allocated heaps. Stacks are allocated in 2 ways: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is assigned by the Malloca function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is released by the compiler without our manual implementation.
Allocation efficiency: The stack is the data structure provided by the machine system, the computer will support the stack at the bottom: allocate the address of the special register storage stack, the stack stack has a special instruction execution, which determines the efficiency of the stack is high. The heap is provided by C + + function library, its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for available enough space, if there is not enough space (possibly due to too much memory fragmentation), It is possible to invoke the system function to increase the memory space of the program data segment, so that there is a chance to divide the memory in sufficient size and then return. Obviously, the heap is much less efficient than the stack.
From here we can see that heap and stack, due to the use of a large number of new/delete, is prone to large amounts of memory fragmentation, because there is no dedicated system support, inefficient, due to the possibility of triggering user-state and nuclear mentality of the switch, memory applications, the cost becomes more expensive. So the stack is the most widely used in the program, even if the call of the function is done by the stack, the parameters in the function call, the return address, the EBP and the local variables are all stored in a stack. So, we recommend that you try to use stacks instead of heaps.
Although the stack has so many advantages, it is not so flexible compared to the heap, sometimes allocating a lot of memory space, or heap better.
Regardless of whether it is a heap or stack, avoid the occurrence of cross-border phenomena (unless you deliberately cross it), because the result of the cross-border is either a program crash, or destroy the program heap, stack structure, produce unexpected results.
comparison between 4.new/delete and Malloc/free
From a C + + perspective, allocating heap space using new can call the class's constructor, and the malloc () function is just a function call, it does not call the constructor, and the parameter it accepts is a unsigned long type. Similarly, delete calls the destructor before releasing the heap space, and the free function does not.
Class time{
Public
Time (int,int,int,string);
~time () {
cout<< "Call Time's destructor by:" <<name<<endl;
}
Private
int hour;
int min;
int sec;
String name;
};
Time::time (int h,int m,int s,string N) {
Hour=h;
Min=m;
Sec=s;
Name=n;
cout<< "Call Time's constructor by:" <<name<<endl;
}
int main () {
Time *t1;
t1= (time*) malloc (sizeof (time));
Free (t1);
Time *t2;
T2=new Time (0,0,0, "T2");
Delete T2;
System ("PAUSE");
return exit_success;
}
Results:
Call time ' s constructor by:t2
Call time ' s destructor by:t2
As you can see from the results, the constructor and destructor of the object can be called using New/delete, and a non-default constructor is called in the example. But when an array of objects is allocated on the heap, only the default constructor can be called, and no other constructors can be called.

From:http://blog.csdn.net/sunlylorn/archive/2008/10/04/3015254.aspx

http://www.oldlinux.org/oldlinux/viewthread.php?tid=7998

Http://www.examda.com/ncre2/C/fudao/20090104/085120193.html

C language Variable declaration memory allocation

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.