Why can I read a dereferenced pointer, but can't write it in C, but can in C++?

-3

I needed to patch a program, so I made a dll that I can inject and on inject it patches one byte of the instruction. The code is pretty simple, the only thing that this time I wanted to write it in C, instead of C++, just of curiosity. But when I load my dll it's thread crashes in place of writing to that pointer. The pointer is 100% and works if you do it with WriteProcessMemory, but by some reason can't be written from a dll, directly from a process. The target executable is x86 and the dll is compiled with gcc. The compilation params look like this: gcc -shared mypatch.c -o mypatch.dll

#include <Windows.h>
#include <stdio.h>
#include <TlHelp32.h>

void main()
{
    AllocConsole(); // Made a console so I can try to read the data, I thought maybe I was getting the wrong address, but I didn't.
    FILE* consoleFile;
    freopen_s(&consoleFile, "CONIN$", "r", stdin);
    freopen_s(&consoleFile, "CONOUT$", "w", stderr);
    freopen_s(&consoleFile, "CONOUT$", "w", stdout);
    DWORD relAddr = 0x123456; // My address
    DWORD addr = (DWORD)GetModuleHandle(NULL) + relAddr; // Adress is relative to the main executable.
    printf("%X", *(byte*)(addr)); // Can read the real byte
    *(byte*)(addr) = 0x90; // Can't write, crash.
    printf("%X", *(byte*)(addr)); // Can't see, crashed.
}

BOOL WINAPI DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    if(dwReason == DLL_PROCESS_ATTACH)
    {
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)main, 0, 0, 0);
    }
    return 1;
}

Error message:

Unhandled exception at 0x70D41355 in SuperCoolApp.exe: 0xC0000005: Access violation writing location 0x123456. occurred
c++
c
pointers
winapi
asked on Stack Overflow Aug 25, 2020 by eLeCtrOssSnake • edited Aug 25, 2020 by eLeCtrOssSnake

1 Answer

-1

The thing wasn't in the C or C++, it was about page protection. So the error was pretty descriptive at itself.

After this confusing try and pray sequence I've decided to look up my C++ code once again and I had found out that my original C++ code had VirtualProtect calls in the other file, which I surely haven't checked before asking. But although this is kind of a shit feeling that I've posted wrong info, I did learn that WriteProcessMemory ignores page protection, and also some tweaks to my C code, which was more of a C++ adaptation from my old code. Should've checked everything first twice. Very thankful to everyone, and kind of sorry.

Just as a confirmation note, everything works identically compared to C and C++. I've rewritten both versions from scratch and they behave totally the same, without the protection override they crash, and with override they both get the job done.

answered on Stack Overflow Aug 25, 2020 by eLeCtrOssSnake

User contributions licensed under CC BY-SA 3.0