Memory allocation method

Source: Internet
Author: User
Tags stack pop

One: Memory allocation method 5 kinds

stack :is the store of variables that are allocated by the compiler when needed and automatically purged when not needed. The variables inside are usually local variables, function parameters, and so on. In a process, the user stack at the top of the user's virtual address space is compiled with it to implement the function invocation.   heap :is the memory blocks allocated by new, their release compiler does not go to the tube, by our application to control, generally a new will correspond to a delete. If the programmer does not release it, the operating system will automatically recycle after the program finishes. The heap can be expanded and shrunk dynamically.   Free Storage area :It is the memory blocks allocated by malloc and so on, and he is very similar to the heap, but it uses free to end his life.   Global/Static storage area :global variables and static variables are assigned to the same piece of memory (in the previous C language, the global variables are divided into initialized and uninitialized global variables and static variables in an area, An uninitialized global variable is in another area adjacent to a static variable: An uninitialized object store can be accessed and manipulated through void* , which is freed by the system at the end of the program, without this distinction in C + +, which collectively occupies the same chunk of memory.   constant Storage:This is a very special storage area, they are stored in a constant, not allowed to modify (of course, you have to pass the improper means can also be modified, and many methods)

Two: The difference between heap and stack

1, different management methods;

For the stack, it is automatically managed by the compiler, without our manual control, and for the heap, the release work is controlled by the programmer and easily generates memory leak.

2, the space size is different;

In general, 32-bit systems, heap memory can reach 4G of 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 (as if it is not clear). Of course, we can modify: Open the project, the Operation menu is as follows: Project->setting->link, select Output in Category, then set the maximum and commit of the stack in the reserve. Note: The reserve minimum value of 4byte;commit is reserved in the virtual memory of the page file, it is set to a large size stack will open up a larger value, may increase the memory overhead and startup time.

3, can produce different fragments;

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 is no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there will never be 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,

4, the growth direction is different;

For the heap, the direction of growth is upward, that is, the direction of the memory address increase, for the stack, its growth direction is downward, is the direction of the memory address is reduced to grow.

5, the distribution method is different;

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 allocated by the malloc 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.

6, the allocation efficiency is different;

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 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.

third, static function static used to control the storage and visibility of variables  Reason :

A variable defined inside a function, when the program executes to its definition, the compiler allocates space on the stack, and the space allocated by the function on the stack is freed at the end of the function execution, creating a problem: What if you want to save the value of this variable in a function to the next call? The easiest way to think of is to define a global variable, but there are many drawbacks to defining a global variable, and the most obvious disadvantage is that it destroys the scope of access to the variable (the variable defined in this function is not only controlled by this function). A data object is required to serve the entire class rather than an object, while at the same time trying not to break the encapsulation of the class, which requires that the member be hidden inside the class and not visible externally.

  function:(1) Hide. When we compile multiple files at the same time, all global variables and functions that do not have a static prefix have global visibility, so use static to define a function with the same name and a variable of the same name in different files without worrying about naming conflicts. (2) The second function of static is to keep the contents of a variable persistent. Variables stored in the static data area are initialized at the start of the program and are the only one initialized. A total of two variables are stored in static storage: Global variables and static variables. (3) The third function of static is initialized to 0 by default. The global variable also has this property because the global variable is also stored in the static data area. In the static data area, all bytes in memory default values are 0x00, sometimes this feature can reduce the workload of the programmer.

Mechanism:

A static data member must exist at the beginning of a program run. Because a function is called in a program run, a static data member cannot allocate space and initialization within any function. In this way, its spatial allocation has three possible places, one is the header file as the outer interface of the class, there is the class declaration, and the second is the inner implementation of the class definition, there is the member function definition of the class, and the third is the global data declaration and definition in front of the main () function of the application.

Static data members are actually allocated space, so they cannot be defined in the declaration of a class (only data members can be declared). A class declaration declares only "dimensions and specifications" of a class and does not actually allocate memory, so it is wrong to write a definition in a class declaration. It also cannot be defined externally in the header file for the class declaration, because that would cause duplicate definitions in multiple source files that use the class.

Static is introduced to tell the compiler that the variables are stored in the program's static store rather than on the stack, and that static data members are initialized sequentially in the order in which they are defined, noting that when static members are nested, the nested members are guaranteed to be initialized. The order of elimination is the inverse order of the initialization.

Advantages:

Can save memory because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to be shared. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is updated once, it is guaranteed that all objects access the same value after the update, which can improve time efficiency. When you reference a static data member, the following format is used:

< class name >::< static member name >

If the access permission for a static data member is allowed (that is, a member of public), the static data member can be referenced in the program in the format described above.

Four: The difference between Malloc and New

1.malloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +. They can all be used to request dynamic memory and free memory

2. For objects of non-intrinsic data types, light Maloc/free cannot meet the requirements of dynamic objects. Objects are automatically executed when they are created, and the object executes the destructor automatically before it dies. The Malloc/free is a library function instead of an operator, not within the control of the compiler, and is not able to impose the task of executing constructors and destructors on Malloc/free.

3. Therefore, the C + + language requires an operator new that can perform dynamic memory allocation and initialization, with an operator delete that can perform cleanup and release of memory work. Note New/delete is not a library function.
4.c++ programs often call C functions, whereas C programs can only use Malloc/free to manage dynamic memory.
5.new can be thought of as the execution of malloc plus constructors. The new pointer is directly with the type information. The void* pointer is returned by malloc.

New Delete actually calls the Malloc,free function on the implementation

6.new object You can use it as an ordinary object, access it with a member function, do not directly access its address space; malloc allocates a memory area, accesses it with pointers, and can move pointers inside.

7.new establishes an object; Alloc allocates a piece of memory.

Same point: can be used to request dynamic memory and free memory

Different points:

(1) The operating objects are different.
malloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +. For objects that are not internal data classes, light Maloc/free cannot satisfy the requirements of dynamic objects. Objects are automatically executed when they are created, and the destructor is executed automatically before the object dies. Because Malloc/free is a library function and not an operator, it is not possible to impose malloc/free on the tasks that execute constructors and destructors without the compiler's control permissions.

(2) The usage is also different.
The prototype of the function malloc is as follows:
void * malloc (size_t size);
Use malloc to request a block length integer type of memory, the program is as follows:
int *p = (int *) malloc (sizeof (int) * length);


We should focus on two elements: type conversion "and" sizeof ".
The type of malloc return value is void *, so type conversion is explicitly performed when malloc is called, and void * is converted to the desired pointer type.
The malloc function itself does not recognize what type of memory to request, it only cares about the total number of bytes in memory.

The prototype of the function free is as follows:
void free (void * memblock);
Why is the free function not as complex as the malloc function? This is because the type of the pointer p and the amount of memory it refers to is known beforehand, and the statement free (p) frees the memory correctly. If p is a null pointer, then free

P No matter how many times the operation is done. If p is not a null pointer, then the free operation of P for two consecutive times causes the program to run incorrectly.

Key points of use of New/delete
Operator new is much simpler to use than the function malloc, for example:
int *P1 = (int *) malloc (sizeof (int) * length);
int *p2 = new Int[length];
This is because new has built-in sizeof, type conversion, and type safety check functionality. For objects that are not internal data types, new initializes the initialization work while creating the dynamic object. If an object has more than one constructor, the new statement can also have multiple forms.

If you create an array of objects with new, you can only use the parameterless constructor of the object. For example
OBJ *objects = new obj[100]; Create 100 Dynamic objects

cannot be written

OBJ *objects = new obj[100] (1);//create 100 dynamic objects while assigning the initial value 1
When releasing an array of objects with delete, be careful not to lose the symbol ' [] '. For example
delete []objects; The right usage
Delete objects; Incorrect use of
The latter is equivalent to delete objects[0], missing another 99 objects.

                                    


 

Memory allocation method

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.