I am following this simple tutorial on how to make a memory scanner in C. For some reason, my main loop just never breaks out.
Here is the code
MEMBLOCK* create_scan(unsigned int pid){
MEMBLOCK *mb_list = NULL;
MEMORY_BASIC_INFORMATION meminfo;
unsigned char *addr = 0;
HANDLE hProc = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
if(hProc){
while(1){
// print the address for debug purpose
printf("%d \r\n", addr);
// loop should break out when the address overflows (return 0)
if(VirtualQueryEx (hProc, addr, &meminfo, sizeof(meminfo)) == 0){
break;
}
#define WRITABLE (PAGE_READWRITE | PAGE_WRITECOPY |PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)
if ((meminfo.State & MEM_COMMIT) && (meminfo.Protect & WRITABLE)){
MEMBLOCK *mb = create_memblock (hProc, &meminfo);
if(mb){
mb->next = mb_list;
mb_list = mb;
}
}
addr = (unsigned char*)meminfo.BaseAddress + meminfo.RegionSize;
}
}
return mb_list;
}
For some reason the output (printf) is this
123863040
125943808
... until ...
2147418112
... all on the sudden ...
-1207959552
...
-243924992
0
65536
loop start again
Any ideas, I’m kinda lost!
The return value from VirtualQueryEx() is the size of the struct it filled in with data. It won’t return zero unless there is an error.
The negative values are just addresses larger than 2GB, being interpreted as negative numbers in the printf(). Once it goes over 4GB it wraps back to 0. As 0 is your initial value, and it worked the first time around, it’ll just start over.
You need a different criteria for exiting your loop.
You might also want to use %p instead of %d to print the current address.