HeapAlloc GlobalAlloc new等内存分配的区别

本文详细解析了Windows环境下的内存管理机制,包括GlobalAlloc和LocalAlloc等函数的区别与联系,以及它们与现代应用程序开发的关系。此外还介绍了堆管理和虚拟内存管理的相关概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.sina.com.cn/s/blog_4bb59dc40100eaxz.html

 

GlobalAlloc是标准内存管理函数,标准内存管理函数都是操作进程的默认堆,所以这个函数是从进程的默认堆中分配内存空间,分配的空间可以是可移动的也可以是不可移动的。可移动的内存是指Windows在需要的时候可以将这个内存移动到另外一个地址.

 

关于GlobalAlloc and LocalAlloc,from MSDN  
   
  The global and local functions supported for porting from 16-bit code, or maintaining source code compatibility with 16-bit Windows. The global and local functions are slower   than other memory management functions and do not provide as many features. Therefore,  new   applications should use the heap functions.However, the global functions are still used with DDE and the clipboard functions.  
   
  Windows memory management does not provide a separate local heap and global heap, as 16-bit Windows does. As a result, there is no difference between the memory objects allocated by the GlobalAlloc and LocalAlloc functions. In addition, the change from a 16-bit segmented memory model to a 32-bit virtual memory model has made some of the related global and local functions and their options unnecessary or meaningless. For example, there are no longer near and far pointers, because both local and global allocations return 32-bit virtual addresses.
 
  Memory objects allocated by GlobalAlloc and LocalAlloc are in private, committed pages with read/write access that cannot be accessed by other processes. Memory allocated by using GlobalAlloc with GMEM_DDESHARE is not actually shared globally as it is in 16-bit Windows. This value has no effect and is available only for compatibility. Applications requiring shared memory for other purposes must use file-mapping objects. Multiple processes can map a view of the same file-mapping object to provide named shared memory. For more information, see File Mapping.

HeapAllock是堆管理函数,堆管理函数可以操作非默认堆(当然也可以操作默认堆),创建一个堆是用HeapCreate,这个函数返回一个堆句柄,然后可以用在HeapAllock函数中,即从返回的这个堆中申请内存空间,HeapAllock申请的内存只能是不可以移动的.

而new则是c++的标准函数,在Windows的VC++编译器中,new在申请内存时最终调用的是GlabalAlloc,不过new还可以调用类的构造函数.

Windows的内存管理除了标准内存管理函数和堆管理函数之外,还有更加底层的虚拟内存管理函数,VirtualAlloc就是一个虚拟内存管理函数.

 

Personal Comprehension

GlobalAlloc分配的内存,还可以调用GlobalLock锁定该内存块(该函数可以被多次调用),在我们没有调用GlobalUnlock之前,该内存块会一直保持有效(即使调用了GlobalFree函数,但如果该内存的锁计数不为0,该内存块也不会被释放掉,依然保持有效)!而如果只调用一次delete,则使用new所分配的内存就会被释放掉.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值