標籤:
new / delete
malloc / free
CoTaskMemAlloc / CoTaskMemFree
IMalloc::alloc / IMalloc/free
GlobalAlloc / GlobalFree
LocalAlloc / LocalFree
HeapAlloc / HeapFree
VirtualAlloc / VirtualFree
VirtualAlloc以頁面為單位(4K)進行分配,是操縱虛擬記憶體的底層函數。
HeapAlloc在指定堆上分配記憶體。
Windows為每個進程設定了一個預設堆,應用程式也可以用HeapCreate建立更多的堆。
GlobalAlloc和LocalAlloc原本為16位環境下的API,Win32為了保持相容性而保留了這兩個函數,但在Win32下已不存在全域堆(所有的堆都是進程私人),所以 GlobalAlloc 和 LocalAlloc 在Win32下意義完全相同,它們都在進程預設堆中進行記憶體配置。需注意的是,在Win32下,GlobalAlloc的字面意思已失效,它並不能在進程間共用資料。微軟強調,GlobalAlloc/LocalAlloc 比 HeapAlloc 要慢,已不再推薦使用,但由於GlobalAlloc/LocalAlloc 具有簡單的使用介面,所以即使在微軟所提供的源碼中,它們仍被大量使用。
malloc是CRT函數,實現方式取決於具體的CRT版本。VC++的malloc系對 HeapAlloc 作簡單的封裝,而Borland C++則選擇自己實現malloc。在應用程式啟動時,CRT建立自己的私人堆,駐留在Win32堆的頂部。
C++中的new先調用 operator new,再調用建構函式產生類對象。而 operator new 在預設情況下調用 malloc 進行記憶體配置。應用程式可以重載 operator new,選擇其他的記憶體配置方式。
CoTaskMemAlloc用於COM對象,它在進程的預設堆中分配記憶體。
IMalloc介面是對 CoTaskMemAlloc/CoTaskMemFree 的再次封裝。
調用關係:
msvcrt.malloc => kernel32.HeapAlloc(ntdll.RtlAllocateHeap)
kernel32.LocalAlloc => ntdll.RtlAllocateHeap
kernel32.GlobleAlloc => ntdll.RtlAllocateHeap
kernel32.HeapAlloc == ntdll.RtlAllocateHeap (映射)
kernel32.VirtualAlloc => kernel32.VirtualAllocEx
kernel32.VirtualAllocEx => ntdll.NtAllocateVirtualMemory
ntdll.RtlAllocateHeap => ntdll.NtAllocateVirtualMemory
ntdll.NtAllocateVirtualMemory => ntdll.KiFastSystemCall
ntdll.KiFastSystemCall => sysenter指令 (0F34)
即:
new -> malloc -> HeapAlloc -> VirtualAlloc -> 驅動程式的_PageAlloc
關於什麼時候使用CoTaskMemAlloc/CoTaskMemFree來申請/釋放記憶體
從網上看來的說法:
The thing is that COM (actually the RPC runtime library, but it‘s easier to blame COM) has an additional requirement for [out] pointers. This requirement is that if the type of an [out] parameter isn‘t a scalar quantity (in other words if it‘s a structure or anything more complicated than a int or float), then the memory pointed to by the [out] parameter needs to be allocated either by MIDL_user_allocate (for RPC) or CoTaskMemAlloc (for COM).
也就是說,如果需要調用COM介面,並且介面中有[out]的參數,且類型不是整形或浮點數之類的基礎資料型別 (Elementary Data Type),就需要調用CoTaskMemAlloc來申請這塊記憶體,並使用完畢後調用CoTaskMemFree來釋放。
http://blog.csdn.net/jiangxinyu/article/details/7792216
Windows平台下主要的記憶體管理途徑