C++的查看指针指向空间的所在的区域(是堆还是栈或者静态)和大小
?? ?char *p2=new char[100];
?? ?*(p2+10)=NULL;
?? ?int t=_msize(p2);
============================================
//指向棧的指針返回1,指向堆的指針返回2,指向靜態(tài)的指針返回3
#include "stdafx.h"
#include <malloc.h>
#include <windows.h>
int pointLocation(LPVOID pObject)
{
?? ?//查詢是否在棧里面
?? ?int nStack(0);
?? ?MEMORY_BASIC_INFORMATION mi = {0};
?? ?DWORD dwGet = VirtualQuery(&pObject, &mi, sizeof(mi));
?? ?printf("棧的起始地址是:0x%08x\n",(DWORD)mi.BaseAddress);
?? ?if (dwGet > 0)
?? ?{
?? ??? ?if(((DWORD)mi.BaseAddress <= (DWORD)pObject && (DWORD)pObject < (DWORD)mi.BaseAddress + mi.RegionSize))
?? ??? ??? ?return 1;
?? ?}
?? ?//查詢是否在堆里面
?? ?DWORD dwHeaps = GetProcessHeaps(0, NULL);
?? ?LPHANDLE pHeaps = new HANDLE[dwHeaps];
?? ?if(pHeaps != NULL)
?? ?{
?? ??? ?MEMORY_BASIC_INFORMATION mi = {0};
?? ??? ?GetProcessHeaps(dwHeaps, pHeaps);
?? ??? ?for(DWORD i=0; i<dwHeaps; ++i)
?? ??? ?{
?? ??? ??? ?VirtualQuery((LPVOID)pHeaps[i], &mi, sizeof(mi));
?? ??? ??? ?printf("第%d個(gè)堆的指針指向地址:%08x\n",i,(DWORD)mi.BaseAddress);
?? ??? ??? ?if((DWORD)pObject >= (DWORD)mi.BaseAddress && (DWORD)pObject < (DWORD)mi.BaseAddress + mi.RegionSize)
?? ??? ??? ?{
?? ??? ??? ??? ?return 2;
?? ??? ??? ??? ?break;
?? ??? ??? ?}
?? ??? ?}
?? ??? ?delete []pHeaps;
?? ?}
?? ?return 3;
}
int _tmain(int argc, _TCHAR* argv[])
{
?? ?/*
?? ?代碼測試的總結(jié):
?? ?用VC6編譯的程序,每次運(yùn)行程序,棧的起始地址都是固定值,堆的值每次都變,棧的地址比堆的地址小,再次申請變量時(shí)棧的地址逐漸變小,堆的地址逐漸變大
?? ?用VS2008編譯的程序,每次運(yùn)行程序,棧的值每次都變,堆的值每次都變,棧的地址比堆的地址小,再次申請變量時(shí)棧的地址逐漸變小,堆的地址逐漸變大
?? ?*/
?? ?static int a=10;
?? ?int b=70;
?? ?int *c=new int;
?? ?*c=90;
?
?? ?int jingtai=pointLocation(&a);
?? ?int zhan=pointLocation(&b);
?? ?int dui=pointLocation(c);
?? ?return 0;
}
總結(jié)
以上是生活随笔為你收集整理的C++的查看指针指向空间的所在的区域(是堆还是栈或者静态)和大小的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用OnCtlColor函数消息打造背景
- 下一篇: VC星号密码查看器源码