C++ LocalAlloc() & LocalSize() & LocalFree ()

关于LocalAlloc function,参考:https://msdn.microsoft.com/en-us/library/windows/desktop/aa366723(v=vs.85).aspx

关于LocalSize function,参考:https://msdn.microsoft.com/en-us/library/windows/desktop/aa366745(v=vs.85).aspx

关于LocalFree function,参考:https://msdn.microsoft.com/en-us/library/windows/desktop/aa366730(v=vs.85).aspx

以下代码摘自:https://msdn.microsoft.com/en-us/library/windows/desktop/aa366723(v=vs.85).aspx

IDE: Code::Blocks 16.01

操作系统:Windows 7 x64

 1 #include <windows.h>
 2 #include <stdio.h>
 3 #include <tchar.h>
 4 
 5 int _cdecl _tmain()
 6 {
 7     LPTSTR pszBuf = NULL;
 8 
 9     pszBuf = (LPTSTR)LocalAlloc(
10         LPTR,
11         MAX_PATH * sizeof(TCHAR));
12 
13     // Handle error condition
14     if (pszBuf == NULL)
15     {
16         _tprintf(TEXT("LocalAlloc failed (%ld)\n"), GetLastError());
17         return 1;
18     }
19 
20     //see how much memory was allocated
21     _tprintf(TEXT("LocalAlloc allocated %d bytes\n"), LocalSize(pszBuf));
22 
23     // Use the memory allocated
24 
25     // Free the memory when finished with it
26     LocalFree(pszBuf);
27 
28     return 0;
29 }

在Code::Blocks 16.01中的运行结果:

IDE: Microsoft Visual Studio Community 2017 15.5.2

操作系统:Windows 7 x64

 1 #include "stdafx.h"
 2 
 3 #include <windows.h>
 4 //#include <stdio.h>    
 5 //#include <tchar.h>
 6 
 7 int _cdecl _tmain()
 8 {
 9     LPTSTR pszBuf = NULL;
10 
11     pszBuf = (LPTSTR)LocalAlloc(
12         LPTR,
13         MAX_PATH * sizeof(TCHAR));
14 
15     // Handle error condition
16     if (pszBuf == NULL)
17     {
18         _tprintf(TEXT("LocalAlloc failed (%d)\n"), GetLastError());
19         return 1;
20     }
21 
22     //see how much memory was allocated
23     _tprintf(TEXT("LocalAlloc allocated %d bytes\n"), LocalSize(pszBuf));
24 
25     // Use the memory allocated
26 
27     // Free the memory when finished with it
28     LocalFree(pszBuf);
29 
30     getchar();
31 
32     return 0;
33 }

 在Microsoft Visual Studio Community 2017 15.5.2中的运行结果:


造成两个IDE的运行结果不一样的原因,是因为TCHAR在两个IDE中的定义不一样。

在Code::Blocks 16.01中,TCHAR是这样定义的:

typedef CHAR TCHAR;
typedef char CHAR;

 而在Microsoft Visual Studio Community 2017 15.5.2中,则是这样的:

typedef wchar_t     TCHAR;

关于LPTR,在Code::Blocks 16.01中,是这样定义的:

#define LPTR 64

而在Microsoft Visual Studio Community 2017 15.5.2中,则这样:

#define LPTR                (LMEM_FIXED | LMEM_ZEROINIT)
#define LMEM_FIXED          0x0000
#define LMEM_ZEROINIT       0x0040

两者是等效的,不过Microsoft Visual Studio Community 2017 15.5.2的定义则比较清晰,一目了然。

关于LMEM_FIXED:Allocates fixed memory. The return value is a pointer to the memory object.

关于LMEM_ZEROINIT:Initializes memory contents to zero.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值