[Solved] C – Read and write bytes from memory


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);
#endif

4

solved C – Read and write bytes from memory