finnthomas finnthomas - 1 year ago 132
C Question

C - Read and write bytes from memory

I want to have a function that can read bytes from memory and another to write like so:

void write_memory(uint32 segment, uint32 offset, char ch);
write_memory(0x750F, 0x00AE, 16);
int read_memory(uint32 segment, uint32 offset);
printf("%d", read_memory(0x750F, 0x00AE));

There's probably a function for this already but even if there is I'd be more interested in writing it myself to see how it's done, so how would I write this function.

Answer Source

This is not "pure C" question, because C language standard doesn't define how to access physical, linear or virtual memory at given address. In many or most environments, operating system won't never let you directly access physical memory, or will only let you access physical memory if you ask it.

For example on Linux with framebuffer, to access framebuffer memory, you have to open framebuffer device in write mode, mmap it to process memory and write to memory starting at address where it was mapped.

In real mode or v86 mode DOS you can directly access video memory, using FAR pointer. In protected mode with DPMI, the DPMI provides means to access physical memory.

Below are examples for Turbo/Borland C++, Microsoft C and DJGPP:

#include <dos.h>
#if defined(__TURBOC__)     
    *(unsigned char far*)MK_FP(0xa000, i) = c;
#elif defined(_MSC_VER)
    *(unsigned char far*)(0xa0000000ul + i) = c;
#elif defined(__DJGPP__) // program is running under DPMI
    dosmemput(&c, 1, 0xa0000 + i);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download