Memory Allocation (Collection)

Source: Internet
Author: User

Globalalloc is a standard memory management function, and the standard memory management function is the default heap of the operating process. Therefore, this function allocates memory space from the default heap of the process, the allocated space can be movable or non-movable. Removable memory means that Windows can move the memory to another address as needed.

Heapallock is a heap management function. The heap management function can operate non-default heap (or the default heap). heapcreate is used to create a heapcreate heap. This function returns a heap handle, it can then be used in the heapallock function, that is, applying for memory space from the returned heap. The memory applied for by heapallock can only be moved.

While new is a standard function of C ++. In Windows VC ++ compiler, new finally calls glabalallock when applying for memory, but new also calls class constructor.

In addition to standard memory management functions and heap management functions, Windows Memory Management also provides a more underlying virtual memory management function. virtualallock is a virtual memory management function.

I. About memory
1. Memory Allocation Method
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. During function execution, the storage units of local variables in the function can be created on the stack.
The storage unit is 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 is running, use malloc or new to apply for any amount of memory.
It is responsible for releasing memory with free or delete at any time. The lifetime of the dynamic memory is determined by us. It is very flexible to use, but the problem is also the most.
2. memory usage Error
Memory Errors are very troublesome. The compiler cannot automatically detect these errors, which can be captured only when the program is running.
Most of these errors do not have obvious symptoms, but they are often invisible and increase the difficulty of error correction. Sometimes the user finds you angrily, but the program does not
If any problem occurs, when you leave, the error occurs again. Common memory errors and their countermeasures are as follows:
* If the memory allocation is unsuccessful, it is used.
New programmers often make this mistake because they do not realize that memory allocation will fail. The common solution is to check before using the memory.
Whether the pointer is null. If you use malloc or new to apply for memory, you should use if (P = NULL) or if (P! = NULL.
* Although the memory allocation is successful, it is referenced before initialization.
There are two main causes for this mistake: first, there is no idea of initialization; second, the default memory initial values are all zero, resulting in reference to the initial values.
Error (for example, array ). There is no uniform standard for the default memory initial values. Although sometimes it is zero, we trust it all.
Trusted users. Therefore, no matter which method is used to create an array, do not forget to assign the initial value. Even the zero value cannot be omitted, so do not bother.
* The memory allocation is successful and initialized, but the operation is beyond the memory boundary.
For example, when an array is used, the subscript "more than 1" or "less than 1" is often performed. Especially in for loop statements, the number of loops is easy to implement.
The array operation is out of bounds.
* Forgot to release the memory, causing memory leakage.
A function containing such errors loses a piece of memory every time it is called. At the beginning, the system had sufficient memory and you could not see the error. Once
The program suddenly died, and the system prompts: the memory is exhausted.
Dynamic Memory application and release must be paired, and the usage of malloc and free in the program must be the same, otherwise there must be errors
(The same applies to new/delete ).
* The memory is released but it is used again.
 
There are three scenarios:
(1) The object calling relationship in the program is too complex, so it is difficult to figure out whether an object has released the memory.
Design the data structure to fundamentally solve the chaos of Object Management.
(2) The Return Statement of the function is incorrect. Be sure not to return the "Pointer" or "Reference" pointing to "stack memory" because there is a function
The data body is automatically destroyed when it ends.
(3) After the memory is released using free or delete, the pointer is not set to null. As a result, a "wild pointer" is generated ".
[Rule 1] after applying for memory with malloc or new, check whether the pointer value is null immediately. Prevent the use of memory with NULL pointer values
Rule 2: Do not forget to assign initial values to arrays and dynamic memory. Avoid using uninitialized memory as the right value.
Rule 3: avoid overrunning the subscript of an array or pointer. Be careful when "more than 1" or "less than 1" is performed.
[Rule 4] dynamic memory application and release must be paired to prevent memory leakage.
[Rule 5] after the memory is released with free or delete, the pointer is immediately set to null to avoid "wild pointer ".

Ii. Details about new, malloc, globalalloc

1. New
The new and delete operators are used to dynamically allocate and revoke memory.
New usage:
1> open up a single variable address space
1) New int; // open up a bucket for storing arrays and return an address pointing to the bucket. int * A = new
INT: assign an int type address to integer pointer.
2) int * A = new int (5) serves the same purpose as above, but at the same time, the integer is assigned to 5
2> open up array space
One-dimensional: int * A = new int [100]; opens up an integer array space of 100
General Usage: New Type [initial value]
Delete usage:
1> int * A = new int;
Delete A; // release the space of a single int
2> int * A = new int [5];
Delete [] A; // release the int array space
To access the struct space opened by new, the variable name cannot be used directly, but can only be accessed through the pointer of the value assignment.
New and delete can be used to dynamically open up and cancel the address space. If a variable is used up during programming (usually an array temporarily stored ),
I need to use it again next time, but I want to save the effort of re-initialization. I can open up a space each time I start using it and undo it after I use it.
2. malloc
Prototype: extern void * malloc (unsigned int num_bytes );
Usage: # I nclude <malloc. h> or # I nclude <stdlib. h>
Function: allocate memory blocks of num_bytes bytes.
Note: If the allocation is successful, the pointer pointing to the allocated memory is returned. Otherwise, the NULL pointer is returned.
When the memory is no longer used, use the free () function to release the memory block.
The syntax of malloc is: pointer name = (data type *) malloc (length), (data type *) indicates pointer.
Description: malloc applies to the system for allocating a specified size of bytes of memory. The return type is void. Void * indicates the undetermined type
Pointer. C, C ++ stipulates that the void * type can be forcibly converted to any other type of pointer.
Working Mechanism of the malloc () function
The essence of the malloc function is that it connects available memory blocks into a long list of so-called idle linked lists. Call malloc
Function, it searches for a memory block that is large enough to meet the needs of user requests along the connection table. Then, split the memory block into two parts:
The size of the small part is equal to the size of the user request, and the size of the other part is the remaining bytes ). Next, pass the memory allocated to the user, and
Return the remaining parts (if any) to the connection table. When the free function is called, it connects the memory block released by the user to the idle chain. To
Finally, the idle link will be cut into many small memory segments. If the user requests a large memory segment, the idle link may not be available.
The segment meets the user requirements. Therefore, the request latency of the malloc function starts to rummaging through the idle chain to check the memory segments.
Sort and merge adjacent small idle blocks into larger memory blocks.

Different from new
We can see from the function declaration. There are at least two differences between malloc and new: New returns a pointer of the specified type and can be automatically calculated as required
Size. For example:
Int * P;
P = new int; // The return type is int * (integer pointer) and the allocated size is sizeof (INT );
Or:
Int * Parr;
Parr = new int [100]; // The returned type is int * (integer pointer) and the allocated size is sizeof (INT) * 100;
While malloc must be calculated by the number of bytes and forcibly converted to the actual type of pointer after the return.
Int * P;
P = (int *) malloc (sizeof (INT ));
1. the malloc function returns the void * type. If you write it as P = malloc (sizeof (INT), the program cannot be compiled,
Error: "You cannot assign void * to int * type variables ". Therefore, you must use (int *) to forcibly convert the data.
Second, the real parameter of the function is sizeof (INT), used to specify the size required for an integer data. If you write:
Int * P = (int *) malloc (1 );
The code can also be compiled, but in fact only one byte memory space is allocated. When you store an integer in it, there will be three bytes
Home can be attributed, and directly "Living in a neighbor's house "! The result is that all the original data in the memory is cleared.

3. globalalloc

About globalalloc, globallock, and globalunlock in VC
Call the globalalloc function to allocate a memory. The function returns the allocated memory handle.
Call the globallock function to lock the memory block. The function accepts a memory handle as a parameter and returns a pointer pointing to the locked memory block.
Needle. You can use this pointer to read and write memory.
Call the globalunlock function to unlock the previously locked memory. This function invalidates the pointer to the memory block.
Call the globalfree function to release memory blocks. You must pass a memory handle to the function.

Globalalloc
Description
Allocate a global memory block
Return Value
Long, returns the global memory handle. Zero indicates failure. Getlasterror is set.
Parameter table
Parameter type and description
Wflags long, a constant sign that defines the allocated memory type, as shown below:
Gmem_fixed allocates a fixed memory block
Gmem_moveable allocates a removable memory block.
Gmem_discardable allocates a memory block that can be discarded.
Gmem_nocompact heap does not accumulate during this function call
No memory block is discarded during the call of the gmem_nodiscard function.
All newly allocated memory blocks of gmem_zeroinit are initialized to zero.
Dwbytes long, number of characters to be allocated
Globallock
Function Description: locks a global memory object and returns the first byte pointer to the object.
Function prototype:
Lpvoid globallock (hglobal hmem)
Parameters:
Hmem: handle of the global memory object. This handle is obtained through globalalloc or globalrealloc.
Return Value:
The call is successful. a pointer to the first byte of the object is returned.
Call failed. null is returned. You can use getlasterror to obtain error information.
Note:
After globallock is called to lock a memory area, you must call globalunlock to unlock it.

Globalunlock
Function Description: unlocks the global memory object.
Function prototype: bool globalunlock (hglobal hmem );
Parameter: hmem: handle of the global Memory Object
Return Value:
Non-zero value. The specified memory object is still locked.
0. Function execution error. You can use getlasterror to obtain error information. If no_error is returned, the memory object has been unlocked.
Note: This function actually removes the lock counter of the memory object by one. If the counter is not 0, multiple globallocks are executed.
To lock this memory object, you need to unlock the corresponding number of globalunlock functions. If the getlasterror function returns an error
The error code is error_not_locked.
Example:
// Malloc memory
Hmem = globalalloc (gmem_moveable | gmem_ddeshare, nsize );
// Lock memory
Pmem = (byte *) globallock (hmem );
..................
// Unlock memory
Globalunlock (hmem );
Globalfree (hmem );
Summary
Flexibility and freedom are a major feature of the C/C ++ language, which poses a challenge for C/C ++ programmers. When the program becomes more and more complex, the memory management is also
It will become more complex and memory problems will occur if you are careful. Memory leakage is one of the most common memory problems. Memory leakage if not serious
In a short period of time, the program will not be significantly affected, which also makes the memory leakage problem highly concealed and not easily discovered. However
Memory leakage is mild. When the program runs for a long time, its destructive power is astonishing. From performance drop to memory depletion, it may even affect other programs.
. In addition, a common feature of memory problems is that memory problems are not very obvious. When exceptions occur
When the time passes, the scene is not where the problem occurs, which makes debugging memory problems very difficult.
Download Windows debug tool, http://www.microsoft.com/whdc/devtools/debugging/default.mspx
After installation, use the gflags.exe tool to open pageheap,
Gflags-P/enable maind.exe/full
Re-use vs to run it in debugging mode, and quickly find the error location, because a mistake in a static function causes
This tool is particularly useful when writing stable server programs.

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.