2

I want to read the entire memory of notepad, and write the output to a text file. If I type something in notepad, I do not find what I type in the output. This is the code:

HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
char* ptr = 0;
MEMORY_BASIC_INFORMATION info;
while(ptr<=(char*)0x7FFF0000)
{
    VirtualQueryEx(hProcess,(LPCVOID)ptr,&info,sizeof(info));
    if((info.AllocationProtect==0x04) || (info.AllocationProtect==0x10) || 
       (info.AllocationProtect==0x20) || (info.AllocationProtect==0x40) || 
       (info.AllocationProtect==0x80) || (info.AllocationProtect==0x02) || 
       (info.AllocationProtect==0x08))
    {
        int bytes_to_read = (int)info.RegionSize;
        char *buffer = NULL;
        buffer = (char *)malloc(info.RegionSize);
        ReadProcessMemory(hProcess,
                          info.BaseAddress,
                          &buffer,
                          bytes_to_read,
                          NULL);
        ofstream out;
        out.open("test.txt",ios_base::app);
        out << buffer;
        out.close();
    }
    ptr += info.RegionSize;
}
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • 1
    AllocationProtect is a *bit mask*. This won't work on a 64-bit version of Windows. Buffer doesn't point to a C string. Solving these problems seems very pointless. – Hans Passant Dec 08 '13 at 22:45

1 Answers1

2

You cannot write a buffer like that. C++ assumes it contains a 0-terminated string.

Try

out.write(buffer, bytes_to_read);

Also open the file with the flags

ios::binary | ios::out
Anders Lindén
  • 6,839
  • 11
  • 56
  • 109