C + + memory allocation cheats-new,malloc,globalalloc detailed

Source: Internet
Author: User
Tags function prototype

C + + memory allocation cheats-new,malloc,globalalloc detailed
_______ only for programmers who can't sleep due to memory allocations

One. About memory

1, memory allocation method

There are three ways to allocate memory:

(1) Allocation from a static storage area. The memory is allocated at the time of program compilation, and the entire running period of the program exists in this block.

。 For example, global variables, static variables.

(2) Create on the stack. When executing a function, the storage unit of the local variable within the function can be created on the stack, and these are saved at the end of the function execution.

The storage unit is automatically released. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.

(3) Allocation from the heap, also known as dynamic memory allocation. The program uses malloc or new to request any amount of memory at run time, and the programmer

When you are responsible for freeing memory with free or delete. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the most.

2. Memory Usage Error
A memory error is a very troublesome thing to happen. These errors are not automatically discovered by the compiler and are usually captured when the program is running.

And most of these errors are not obvious symptoms, and the hidden, increased the difficulty of error. Sometimes the user angrily to find you, the program is not

Any problems occur, you go, the wrong again attack. Common memory errors and their countermeasures are as follows:
* The memory allocation was unsuccessful, but it was used.

Novice programmers often make this mistake because they are unaware that the memory allocation will not succeed. A common workaround is to check before using memory

Whether the pointer is null. If you are using malloc or new to request memory, you should use if (p==null) or if (P!=null) for error-proof handling.

* The memory allocation succeeds, but it is not initialized to reference it.

There are two main causes of this error: one is the idea of no initialization, and the other is to mistakenly assume that the default initial value of the memory is all zero, leading to the reference value

Errors (such as arrays). There is no uniform standard for what the default initial value of memory is, although sometimes it is zero, and we would rather believe it.

Credible it has. So no matter how to create an array, do not forget to assign the initial value, even if it is assigned 0 values can not be omitted, do not bother.

* The memory allocation succeeds and has been initialized, but the operation crosses the memory boundary.

For example, the use of arrays often occurs when the subscript "more 1" or "less 1" operation. Especially in a for-loop statement, the number of cycles is easily

Error, causing array operations to be out of bounds.

* Forgot to release memory, causing memory leaks.

The function that contains this error loses one piece of memory each time it is called. At first, the system has plenty of memory and you can't see the error. There was a time.

The program suddenly dies, the system appears prompt: memory exhaustion.

Dynamic memory application and release must be paired, the program malloc and free use must be the same number, or there must be errors

(New/delete).

* Release the memory and continue to use it.
 
There are three types of cases:

(1) The object invocation in the program is too complex, it is difficult to find out whether an object has already freed the memory, this time should be re-

Design data structure, fundamentally solve the chaotic situation of object management.

(2) The return statement of the function is incorrectly written, note that you do not return a pointer to "stack memory" or "reference" because the memory is in the letter

is automatically destroyed at the end of the number body.

(3) After releasing memory with free or delete, the pointer is not set to null. Causes the "wild pointer" to be produced.

After rule 1 has requested memory with malloc or new, you should immediately check that the pointer value is NULL. Prevent use of memory with a pointer value of NULL

Rule 2 Do not forget to assign an initial value to both arrays and dynamic memory. Prevents memory that is not initialized from being used as the right value.

"Rule 3" avoids array or pointer subscript out of bounds, especially beware of "more 1" or "less 1" operations.

"Rule 4" the request and release of dynamic memory must be paired to prevent a memory leak.

"Rule 5" after releasing memory with free or delete, immediately set the pointer to NULL to prevent the "wild pointer" from being produced.


Two. Detailed New,malloc,globalalloc

1. New

Operators for dynamic allocation and revocation of memory by the new and delete operators

New usage:

1> opening a single variable address space

1) New int; Opens a storage space for the array, returning an address to that storage space. int *a = new

int is the assignment of an int-type address to an integer pointer a.

2) int *a = new int (5) acts as above, but assigns integers to 5 at the same time

2> Open Array Space

One-dimensional: int *a = new int[100]; Open an integer array space of size 100

General usage: new type [initial value]

Delete usage:

1> int *a = new int;

Delete A; Free space for a single int

2>int *a = new Int[5];

delete [] A; Free int array space

To access the structure space opened by new, it cannot be accessed directly from the variable name, but only through the assigned pointer.

Use new and delete to dynamically open and revoke the address space. If you run out of a variable (typically an array that is temporarily stored) when you are in a program,

The next time you need to use it, but you want to save the re-initialization effort, you can open up a space each time you start using it, and then undo it when you're done.

2. malloc
Prototype: extern void *malloc (unsigned int num_bytes);
Usage: #i nclude <malloc.h> or #i nclude <stdlib.h>
Function: Allocates a memory block of length num_bytes bytes
Note: If the assignment succeeds, it returns a pointer to the allocated memory, otherwise the null pointer is null.
Use the free () function to release memory blocks when memory is no longer in use.
The syntax for malloc is: pointer name = (data type *) malloc (length), (data type *) represents the pointer.
Description: malloc allocated memory space to the system to allocate a specified size byte. The return type is the void* type. void* indicates an indeterminate type

The pointer. c,c++ Specifies that the void* type can be cast to any other type of pointer.

Working mechanism of malloc () function
The real body of the malloc function now, it has a so-called idle list that connects the available memory blocks to a long listing. Call malloc

function, it looks for a block of memory along the join table that is large enough to satisfy the user's request. The memory block is then split in two (a large

Small is equal to the size of the user request, and the size of the other is the remaining bytes. Next, pass the memory allocated to the user to the user and

Return the remaining piece (if any) to the connection table. When the free function is called, it connects the memory blocks freed by the user to the idle chain. To

Finally, the idle chain is cut into a lot of small memory fragments, if the user requests a large memory fragment, then the idle chain may not be able to

A fragment that satisfies the user's requirements. The malloc function then requests a delay and begins to rummage through the memory fragments on the idle chain,

To organize and merge the adjacent small free blocks into larger chunks of memory.

Different from new
As you can see from the function declaration. malloc and new are at least two different: new returns a pointer of the specified type, and can automatically calculate the required

To size. Like what:
int *p;
p = new int; The return type is the int* type (integer pointer), and the allocation size is sizeof (int);
Or:
Int* Parr;
Parr = new int [100]; The return type is the int* type (integer pointer), and the allocation size is sizeof (int) * 100;
malloc, however, must be computed by us to calculate the number of bytes and forcibly converted to a pointer of the actual type after the return.
int* p;
p = (int *) malloc (sizeof (int));
First, the malloc function returns the void * type if you write: p = malloc (sizeof (int)); The program cannot be compiled,

Error: "Cannot assign void* to int * type variable". Therefore, the cast must be passed (int *).
Second, the argument to the function is sizeof (int), which indicates the size required for an integral type of data. If you write:
int* p = (int *) malloc (1);
Code can also be compiled, but in fact only allocates 1 bytes of memory space, when you put an integer inside, there will be 3 bytes without

Home can be returned, and directly "live in the neighbor's house"! The result is that the contents of the original data in the back memory are all emptied.


3. GlobalAlloc

About Globalalloc,globallock,globalunlock in VC

Call the GlobalAlloc function to allocate a chunk of memory, which returns the allocated memory handle.
Call the GlobalLock function to lock the memory block, which takes a memory handle as a parameter and then returns a pointer to the block of memory that is locked

Needle. You can use this pointer to read and write memory.
Call the GlobalUnlock function to unlock previously locked memory, which invalidates pointers to memory blocks.
Call the GlobalFree function to free the memory block. You must pass a memory handle to the function.

GlobalAlloc
Description
Allocating a global block of memory
return value
A Long that returns a global memory handle. Zero indicates failure. Will set GetLastError
Parameter table
Parameter type and description
Wflags Long, a constant flag defined for the allocated memory type, as follows:
Gmem_fixed allocating a fixed block of memory
Gmem_moveable allocating a removable block of memory
Gmem_discardable allocating a memory block that can be discarded
The Gmem_nocompact heap does not accumulate during this function call
No memory block is discarded during Gmem_nodiscard function call
Gmem_zeroinit all newly allocated memory blocks are initialized to 0
Dwbytes Long, the number of characters to allocate

GlobalLock
Function Description: Locks a global memory object, returning a pointer to the first byte of the object
Function Prototypes:
LPVOID GlobalLock (Hglobal hmem)
Parameters:
Hmem: A handle to the global memory object. This handle is obtained by GlobalAlloc or GlobalRealloc.
return value:
The call succeeds, returning a pointer to the first byte of the object
Call failed, return NULL, can use GetLastError to get error message
Attention:
After calling GlobalLock to lock a chunk of memory, be sure to call GlobalUnlock to unlock

GlobalUnlock
function function Description: Unlock global memory objects that are locked
Function prototype: BOOL GlobalUnlock (Hglobal hmem);
Parameter: Hmem: Handle to Global Memory object
return value:
Non-0 value, the specified memory object is still in the locked state
0, function execution error, can use GetLastError to get error message, if return no_error, it means that the memory object has been unlocked
Note: This function is actually to reduce the lock counter of the memory object by one, if the counter is not 0, it means to execute too many GlobalLock

function to lock the memory object, which requires a corresponding number of globalunlock functions to unlock it. If an error is returned through the GetLastError function

Code is error_not_locked, it means no lock or unlock.

Example:
Malloc Memory
Hmem = GlobalAlloc (gmem_moveable | Gmem_ddeshare, nSize);
Lock Memory
Pmem = (BYTE *) GlobalLock (HMEM);
..................
Unlock Memory
GlobalUnlock (HMEM);
GlobalFree (HMEM);

Three summary

Flexible freedom is a major feature of the C + + language, and this is a problem for C + + programmers. As programs become more complex, the management of memory

becomes more complex, and there is a memory problem with a slight carelessness. Memory leaks are one of the most common memory problems. Memory leaks if not very serious

, in a short period of time on the program will not have much impact, which also makes the memory leak problem has a strong concealment, not easy to be discovered. But not in the tube

How slight the leak is, when the program is running for a long time, its destructive power is staggering, falling from performance to memory exhaustion, and even affecting other programs

of normal operation. In addition, a common feature of memory problems is that the memory problem itself does not have a very obvious phenomenon, when there is an abnormal phenomenon occurred

Time passes by, its scene has not appeared the problem at the scene, this has caused the debugging memory question to have the very big difficulty.

C + + memory allocation cheats-new,malloc,globalalloc detailed

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.