About memory Functions GlobalLock (), GlobalAlloc (), GlobalUnlock () Usage __ function

Source: Internet
Author: User
Tags function prototype garbage collection reserved win32
Global and local memory management from: About memory Functions GlobalLock (), GlobalAlloc (), GlobalUnlock () usage

1. Why use the GlobalLock () function

C + + code

Hglobal Himagememory=globalalloc (gmem_moveable, dwfilesize); Assigning global memory to a picture
void *pimagememory=globallock (himagememory); Lock memory
DWORD dwreadedsize; Save the actual read file size
ReadFile (hfile, Pimagememory, dwFileSize, &dwreadedsize, NULL); Reading pictures into global memory
GlobalUnlock (himagememory); Unlock Memory
CloseHandle (hfile); Close file handle
IStream *pistream;//creates a IStream interface pointer to save the picture stream

Answer:

Lobalalloc application of the memory is divided into two kinds, one is gmem_fixed, the other is gmem_moveable.
The difference as long as the gmem_moveable type of memory operating system can be moved, such as the heap has several small memory,
When a larger chunk of memory is applied, the operating system moves the gmem_moveable type of memory to merge a chunk.
Because the gmem_moveable is removable, the handle is identified and cannot be identified with a memory address.
The memory address is obtained by GlobalLock by a handle when used.

For the gmem_fixed type, the handle returned by the function is a memory pointer that can be used directly as a memory pointer.

Source: http://topic.csdn.net/u/20100802/17/2e66b3ef-285d-43da-b5a2-60f8d0665fbd.html

2. VC in the use of globalalloc,globallock,globalunlock and questions

The GlobalAlloc function is called to allocate a chunk of memory that returns the allocated memory handle.
Call the GlobalLock function to lock a block of memory that takes a memory handle as a parameter and then returns a pointer to the locked block of memory. You can use this pointer to read and write memory.
Call the GlobalUnlock function to unlock previously locked memory, which invalidates the pointer to the memory block.
Call the GlobalFree function to free the memory block. You must pass the function a memory handle.

GlobalAlloc
Description
Allocating a global memory block
return value
Long, which returns the global memory handle. Zero indicates failure. Will set GetLastError
Parameter table
Parameter type and description
Wflags Long, a constant flag that defines the allocated memory type, as follows:
Gmem_fixed allocate a block of fixed memory
Gmem_moveable allocate a removable memory block
Gmem_discardable allocate a disposable memory block
Gmem_nocompact Heap does not accumulate during this function call
No memory blocks are discarded during gmem_nodiscard function calls
Gmem_zeroinit the newly allocated memory blocks are all initialized to 0
Dwbytes Long, number of characters to assign
Annotations
If gmem_fixed is specified, the return value is the actual memory address to use-the pointer (GlobalLock returns the same value)-so there is no need to perform a globallock/globalunlock operation when using a fixed block of memory
Because WIN32 employs advanced memory management scenarios, there is no benefit in using removable blocks of memory
The memory block allocated with this function is allowed within 8-bit bounds
"Attached" questions about GlobalAlloc
--------------------------------------------------------------------------------
Q: When allocating a global block of memory using GlobalAlloc, the difference between allocating a fixed block of memory using gmem_fixed and allocating a removable memory block using gmem_moveable. (Please be more specific)
Whether there are differences in their efficiency.
Why in some source code, and then use the GMEM_MOVEABLE flag to allocate memory, will use the GlobalFree of the memory handle it returned to release the operation of the statement commented out, or simply do not write. Wouldn't it be necessary to do so?
--------------------------------------------------------------------------------
A: Gmem_moveable is to allow the operating system (or application) to manage the memory heap, when necessary, the operating system can move the memory block to obtain larger blocks, or to merge some free memory blocks, also known as "garbage collection", it can improve memory utilization. In general, the memory heap space is managed by the user, and the Windows operating system does not intervene. If the following conditions exist, that is, there are 10 1K of free blocks in the heap, then if you directly request a 5K of memory space, you will get unsuccessful information. But if the other already occupied memory block is movable, then the system can move these blocks of memory, merging a 5k block of memory, and successfully allocated to the user to use. Its spatial efficiency is at the cost of run-time efficiency.

GlobalLock
Function Description: Locks a global Memory object, returns a pointer to the first byte of the object
Function Prototypes:
LPVOID GlobalLock (Hglobal hmem)
Parameters:
Hmem: The handle of the global memory object. This handle is obtained by GlobalAlloc or GlobalRealloc.
return value:
The call succeeded, returning a pointer to the first byte of the object
Call failed, return NULL, can use GetLastError to get error message
Attention:
Once the GlobalLock has been called to lock a block of memory, be sure to call GlobalUnlock to unlock it.

GlobalUnlock
Function Description: Unlocking a locked global memory object
Function prototype: BOOL GlobalUnlock (Hglobal hmem);
Parameters: Hmem: Handle to Global Memory object
return value:
Non 0 value, the specified memory object is still in a locked state
0, the function execution error, you can use GetLastError to get the 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 functions to lock the memory object and need the corresponding number of globalunlock functions to unlock.
If the error code returned by the GetLastError function is error_not_locked, it means that it is unlocked or unlocked.

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


1. HeapAlloc:
The explanation on MSDN is: HeapAlloc is the allocation of memory from the heap, and the allocated memory is not removable (that is, if there is no contiguous space to meet the size of the allocation, the program can not take advantage of other scattered space, resulting in the allocation failure), the allocation method from a specified address began to allocate, Unlike Gloabalalloc, which is allocated from the global heap, this may be global or local. The function prototype is:
LPVoid
HeapAlloc (
HANDLE Hheap,
DWORD dwflags,
size_t dwbytes
);
Hheap is the process heap memory start position.
Dwflags is the flag that allocates heap memory. Including Heap_zero_memory, even if the allocated space is zero.
Dwbytes is the size of the allocation heap memory.
The corresponding free space function is heapfree.
2. GlobalAllocThis function is used to allocate memory from the global heap for use by the program, and the function prototype is:
Hglobal GlobalAlloc (
UINT Uflags,
size_t dwbytes
);
Uflags parameter meaning
Combination of ghnd gmem_moveable and Gmem_zeroinit
gmem_fixed allocates fixed memory, the return value is a pointer
Gmem_moveable allocates active memory, in Win32, the memory block cannot move in physical memory, but can move in the default heap. The return value is the handle of the memory object, and the function globallock the handle into a pointer
Gmem_zeroinit Initialize memory content to zero
Combination of gptr gmem_fixed and Gmem_zeroinit
In general, when we are programming, the memory allocated to the application can be moved or can be discarded, this allows for limited memory resources to be fully utilized, so, at a certain time we allocate the memory of the address is uncertain, because he is able to move, so we have to lock the block of memory, Here the application needs to invoke the API function GlobalLock function to lock the handle. as follows: Lpmem=globallock (HMEM); This allows the application to access this block of memory. So we use globalallock, usually with the use of GlobalLock, of course, when not using memory, we must remember to use GlobalUnlock, otherwise the locked block of memory can not be used by other variables.
GlobalAlloc the corresponding free space function is globalfree.
3. LocalAllocThis function is used to allocate memory from the local heap for use by the program, and the function prototype is:
Hlocal LocalAlloc (
UINT Uflags,
size_t ubytes
);
Parameters with GlobalAlloc.
There is a difference in 16-bit Windows, because 16-bit Windows uses a global heap and a local heap to manage memory, each application or DLL is loaded into memory, the code snippet is loaded into the global heap, and the system assigns a 64KB data segment from the global heap to the local heap of the instance for each instance That holds the stack and all global or static variables for the application. Localalloc/globalalloc is used to allocate memory in a local heap or global heap, respectively.
Because the local heap of each process is small, allocating memory in the local heap is limited by space. But this heap is private to each process, relatively safe to allocate data, and data access errors do not affect the entire system.
The memory allocated in the global heap is shared for each process, and each process has access to that memory as long as it has a handle to the memory block, but each global memory space requires additional memory overhead, resulting in a waste of allocation. And once a serious error occurs, it may affect the stability of the entire system.
However, in Win32, each process has only one missing private heap, which can only be accessed by the current process. It is also not possible for an application to access system memory directly. Therefore, the global heap and the local heap in the Win32 point to the missing heap of the process. Allocating memory with Localalloc/globalalloc does not make any difference. Even the LocalAlloc allocated memory can be released by GlobalFree. So in Win32 programming, without noticing the difference between local and global, the general memory allocation is equivalent to HeapAlloc (GetProcessHeap (),...).
LocalAlloc the corresponding release function is Lockfree.
4. VirtualAllocThe function is to call the virtual address space of the process, book or submit part of the page, if used for memory allocation, and the assignment type does not specify Mem_reset, the system will automatically set to 0; its function prototype:
LPVOID VirtualAlloc (
LPVOID lpaddress,//region to reserve or commit
size_t dwsize,//size of Region
DWORD Flallocationtype,//type of allocation
DWORD flprotect//type of Access Protection
);
VirtualAlloc can keep a large area of memory by repeatedly invoking a part or all of a zone in parallel. Multiple calls committing the same area do not cause failures. This allows an application to retain memory and submit pages that will be written. When this method is not valid, it releases the application by detecting the status of the reserved page to see if it has been committed before the commit call.
VirtualAlloc the corresponding release function is VirtualFree.
5. Mallocmalloc and free are standard library functions for c++/c languages that can be used to request dynamic memory and release memory. For objects that are not internal data types, Malloc/free cannot meet the requirements of dynamic objects. Objects are created with the constructor automatically executed, and the destructor is automatically executed before the object dies. Because Malloc/free is a library function and not an operator, it is not possible to impose the task of executing constructors and destructors on Malloc/free without the compiler controlling permissions.
6. NewNew/delete is the operator of C + +. Can be used to request dynamic memory and free memory. The C + + language requires a new operator to complete dynamic memory allocation and initialization, with an operator delete that cleans and frees up memory work. Note that New/delete is not a library function. C + + programs often have to call functions, while C programs can only use Malloc/free to manage dynamic memory. New is an operator, and what "+", "-", "=" ... Have the same status.
Malloc is a function of allocating memory for you to call.
New is a reserved word and does not require header file support.
malloc requires header file library function support. New creates an object,
malloc allocates a piece of memory.
New object you can use as an ordinary object, access by member function, do not directly access its address space
malloc allocates an area of memory that is accessed with pointers, and can also move pointers inside.
A memory leak can be checked for malloc or new, except that new can indicate the line of that file, and the malloc does not have the information. New can be considered the execution of the malloc constructor. The pointer to new is directly with type information. Instead, malloc returns a void pointer.

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.