複製鏈接
請複製以下鏈接發送給好友

LocalAlloc

鎖定
LocalAlloc,This function allocates the specified number of bytes from the heap.
這個函數從堆中分配指定大小的字節數。
中文名
LocalAlloc
類    別
編程函數
作    用
從堆中分配指定大小的字節數
用    處
計算機

目錄

LocalAlloc格式

HLOCAL LocalAlloc(
UINT uFlags,
UINT uBytes
);
Parameters uFlags [in] Specifies how to allocate memory. If zero is specified, the default is the LMEM_FIXED flag. The following table shows the flags for this parameter. The parameter is one of these flags. ValueDescriptionLMEM_FIXED Allocates fixed memory. The return value is a pointer to the memory object.LPTR Combines the LMEM_FIXED and LMEM_ZEROINIT flags.LMEM_ZEROINIT Initializes memory contents to zero.uBytes [in] Specifies the number of bytes to allocate.

LocalAlloc參數

uFlags[in]指定怎樣去分配內存。如果zero被指定,默認的是LMEM_FIXED標誌。此參數有三種標誌:
LMEM_FIXED:分配固定內存,返回值是指向一個內存對象的指針
LMEM_ZEROINIT:初始化內存內容為zero。
LPTR:結合了LMEM_FIXED和LMEM_ZEROINIT這兩種標誌。
LMEM_MOVEABLE:分配可移動內存。
LMEM_DISCARDABLE:分配可刪除的內存。
uBytes:[in]指定要分配的字節數。
Return Values
A handle to the newly allocated memory object indicates success.
NULL indicates failure.
To get extended error information, call GetLastError.
返回值:成功則返回一個指向新分配的內存對象的句柄。
NULL表明函數失敗。
要得到更多的錯誤信息的話,調用GetLastError。
Remarks
If the heap does not contain sufficient free space to satisfy the request, LocalAlloc returns NULL. Because NULL is used to indicate an error, virtual address zero is never allocated. Therefore, it is easy to detect the use of a NULL pointer.
If this function succeeds, it allocates at least the amount requested. If the amount allocated is greater than the amount requested, the process can use the entire amount.
To determine the number of bytes allocated, use the LocalSize function.
To free the memory, use the LocalFree function.
For Windows CE versions 1.0 and 1.01, the local heap for each process cannot exceed 1 MB. However, a process can create multiple heaps using the HeapCreate function and each heap can be up to 1 MB.
For Windows CE versions 1.0 through 2.12, allocating memory approximately 0 to 7 bytes under 192K in size causes the corresponding call to LocalFree to fail for certain memory blocks in this size range. The return code is ERROR_INVALID_PARAMETER.

LocalAlloc其他信息

該函數用局部內存對象的分配(全局內存對象的分配使用函數GlobalAlloc)。
如果堆中沒有充足的自由空間去滿足我們的需求,LocalAlloc返回NULL。因為NULL被使用去表明一個錯誤,虛擬地址zero從不被分配。因此,很容易去檢測NULL指針的使用。
如果函數成功的話,它至少會分配我們指定大小的內存。如果分配給我們的數量多於我們指定的話,這個進程能使用整個數量的內存。
可以使用LocalSize函數去檢測被分配的字節數。
可以使用LocalFree函數去釋放這段內存。
對於分配的可移動內存、可刪除內存讀取前需加鎖(相關函數LocalLock)否則將無法正常讀取,讀取完成後需解鎖(相關函數LocalUnlock)否則無法使用LocalFree函數來釋放內存。
對於Windows CE versions 1.0 and 1.01,每個進程的本地堆不能超過1MB。然而,一個進程能夠使用HeapCreate函數創建多個堆,而且每個堆分配的字節能最大能達到1MB。
對於Windows CE版本1.0到2.12,分配在192K數量範圍內的約為0到7個字節的大小內存——在這一尺寸範圍的某些內存塊——引起相應的調用LocalFree失敗。返回的代碼是ERROR_INVALID_PARAMETER。
Requirements
OS Versions: Windows CE 1.0 and later.
Header: Winbase.h.
Link Library: Coredll.lib.