C++内存查找实例
本文实例讲述了C++内存查找的方法,分享给大家供大家参考。具体如下:
windows程序设计中的内存查找功能,主程序代码如下:
//MemRepair.cpp:定义控制台应用程序的入口点。 // #include"stdafx.h" #include<Windows.h> BOOLFindFirst(DWORDdwValue); BOOLFindNext(DWORDdwValue); HANDLEg_hProcess; DWORDg_arList[1024]; DWORDg_nListCnt; BOOLCompareAPage(DWORDdwBaseAddr,DWORDdwValue) { //读取一页内存 BYTEarBytes[4096]; BOOLbRead=::ReadProcessMemory(g_hProcess,(LPVOID)dwBaseAddr,arBytes,4096,NULL); if(bRead==FALSE) { returnFALSE; } DWORD*pdw; for(inti=0;i<4096-4;i++) { pdw=(DWORD*)&arBytes[i]; if(pdw[0]==dwValue) { g_arList[g_nListCnt++]=dwBaseAddr+i; } /*出错,应该将地址先转换成DWORD*,即指向DWORD的地址,然后再取[0] if((DWORD)&arBytes[i]==dwValue) { g_arList[g_nListCnt++]=dwBaseAddr+i; } */ } if(g_nListCnt>1024) { printf("thepositionislargethan1024.."); returnFALSE; } returnTRUE; } BOOLFindFirst(DWORDdwValue) { constDWORDdwOneGB=1*1024*1024*1024;//1GB constDWORDdwOnePage=4*1024;//4K DWORDdwBase; OSVERSIONINFOversionInfo={0}; versionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); ::GetVersionEx(&versionInfo); if(versionInfo.dwPlatformId== VER_PLATFORM_WIN32_WINDOWS)//win98 { dwBase=4*1024*1024;//4MB } else { dwBase=64*1024;//64KB } //从开始地址到2GB的空间查找 for(;dwBase<2*dwOneGB;dwBase+=dwOnePage) { CompareAPage(dwBase,dwValue); } returnTRUE; } BOOLFindNext(DWORDdwValue) { DWORDdwOriCnt=g_nListCnt; DWORDdwReadValue; BOOLbRet=FALSE; g_nListCnt=0; for(inti=0;i<dwOriCnt;i++) { if(::ReadProcessMemory(g_hProcess,(LPVOID)g_arList[i],&dwReadValue,sizeof(DWORD),0)) { if(dwReadValue==dwValue) { g_arList[g_nListCnt++]=g_arList[i]; bRet=TRUE; } } } returnbRet; } voidShowList() { for(inti=0;i<g_nListCnt;i++) { printf("%08lX\n",g_arList[i]); } } BOOLWriteMemory(DWORDdwAddr,DWORDdwValue) { //出错的情况:写入的是&dwValue,而不是(LPVOID)dwValue returnWriteProcessMemory(g_hProcess,(LPVOID)dwAddr,&dwValue,sizeof(DWORD),NULL); } int_tmain(intargc,_TCHAR*argv[]) { g_nListCnt=0; memset(g_arList,0,sizeof(g_arList)); charszCommandLine[]="c:\\testor.exe"; STARTUPINFOsi={sizeof(STARTUPINFO)}; si.dwFlags=STARTF_USESHOWWINDOW; si.wShowWindow=TRUE; PROCESS_INFORMATIONpi; BOOLbRet=CreateProcess(NULL,szCommandLine,NULL,NULL,FALSE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi); if(bRet==FALSE) { printf("createProcessfailed..."); return-1; } ::CloseHandle(pi.hThread); g_hProcess=pi.hProcess; //输入修改值 intiVal; printf("InputiVal="); scanf("%d",&iVal); //进行第一次查找 FindFirst(iVal); //打印结果 ShowList(); //再次查找 while(g_nListCnt>1) { printf("inputiVal:\n"); scanf("%d",&iVal); FindNext(iVal); ShowList(); } //修改值 printf("inputnewvalue:\n"); scanf("%d",&iVal); if(WriteMemory(g_arList[0],iVal)) { printf("writesuc..."); } ::CloseHandle(g_hProcess); return0; }
测试用的程序代码如下:
#include"stdafx.h" #include<stdio.h> intg_nNum=1003; int_tmain(intargc,_TCHAR*argv[]) { inti=200; while(1) { printf("i=%d,&i=%08lX...g_nNum=%d,&g_nNum=%08lX\n\n",i--,&i,--g_nNum,&g_nNum); getchar(); } return0; }
希望本文所述对大家的C++程序设计有所帮助。