mercredi 29 juin 2016

Program crashes when trying to dereferrence a non null char*

I'm trying to read from the memory of a different process's module using ReadProcessMemory in the winapi:

BOOL WINAPI ReadProcessMemory(
  _In_  HANDLE  hProcess,
  _In_  LPCVOID lpBaseAddress,
  _Out_ LPVOID  lpBuffer,
  _In_  SIZE_T  nSize,
  _Out_ SIZE_T  *lpNumberOfBytesRead
);

The line causing my program to crash is: myfile << *buffer; and I know it's causing it because when I comment the line out my program works fine. Here are all lines that are relevant:

int inc = 0;
char* buffer = new char;
fstream myfile ("C:\\Users\\Edward Severinsen\\Desktop\\temp-memory.txt", ios::app);
if(!(myfile.is_open())){cout << "Unable to open file\n";system("pause");}

...

if(Module32First(snapshot, &modEntry) == FALSE){printf("Mod32First failed: %d", (int)GetLastError());CloseHandle(snapshot);return 1;}
while(ReadProcessMemory(proc, modEntry.modBaseAddr+inc, &buffer, sizeof(buffer), NULL) != 0)
{
if(buffer == nullptr)
        {
            cout << "buffer is a null pointer\n";
            system("pause");
            CloseHandle(snapshot);
            CloseHandle(proc);
            return 1;
        }
        printf("%c", buffer);
        myfile << *buffer;
        inc++;
    }

And even though I don't think it's necessary here's all the code in my program:

#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#define DWNULL 0xFFFFFFFF
using namespace std;

int main()
{
    DWORD pid = DWNULL;
    MODULEENTRY32 modEntry;
    int inc = 0;
    char* buffer = new char;
    fstream myfile ("C:\\Users\\Edward Severinsen\\Desktop\\temp-memory.txt", ios::app);
    if(!(myfile.is_open())){cout << "Unable to open file\n";system("pause");}

    modEntry.dwSize = sizeof(MODULEENTRY32);

    cout << "PID: " << flush;
    cin >> pid;

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
    if(snapshot == INVALID_HANDLE_VALUE){printf("Snapshot failed: %d", (int)GetLastError());CloseHandle(snapshot);return 1;}
    HANDLE proc = OpenProcess(PROCESS_VM_READ, FALSE, pid);
    if(proc == INVALID_HANDLE_VALUE){printf("Error: %d", (int)GetLastError());return 1;}
    if(Module32First(snapshot, &modEntry) == FALSE){printf("Mod32First failed: %d", (int)GetLastError());CloseHandle(snapshot);return 1;}

    while(ReadProcessMemory(proc, modEntry.modBaseAddr+inc, &buffer, sizeof(buffer), NULL) != 0)
    {
        if(buffer == nullptr)
        {
           cout << "buffer is a null pointer\n";
           system("pause");
           CloseHandle(snapshot);
           CloseHandle(proc);
           return 1;
        }
        printf("%c", buffer); //Prints first character then goes to next line and crashes.
        myfile << *buffer;
        inc++;
    }
    system("pause");
}

Aucun commentaire:

Enregistrer un commentaire