简体   繁体   中英

How to write data at a specific memory location? C++

Following is the code I used to write unsigned data at 0x10000000. The program has been compiled but run failed.

void load_program(unsigned base_address){
    char* IM=reinterpret_cast <char*>(base_address);
    unsigned a=0;
    *IM=a;
}
int main(int argc, char** argv) {
    unsigned address=0x10000000;    
    load_program(address);
    return 0;
}

Operating systems actually don't let you access memory you didn't allocate through the OSs interface. Memory management is pretty complex (refer to https://en.wikipedia.org/wiki/Paging as an example).

Your code should run on a device without an OS, like an Arduino.

Anyway if you want to manage your own memory, maybe you can first allocate a chunk by calling malloc (which is oldschool C style) like

int * pointer = 0;
int size = 50000;
pointer = (int*) malloc(size); //pointer now points to the beginning

On Linux platform OS won't allow user(user space process) to select one random address and put the data onto that because a normal user space process doesn't have access to modify/write on privileged area of RAM.

char* IM = 0x10000000; 
*IM = 10; /** It won't allow you to access */

On Linux you can use mmap. You have to run as root. I use this to reach the PL area of a Xilinx SoC.

#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
...
unsingned int addr = 0x10000000;
unsigned int base = addr & 0xFFFF0000;
unsigned int offset = addr & 0x0000FFFF;
memfd = open("/dev/mem",O_RDWR);
char * baseaddr = static_cast<char *>(mmap(0, 0x10000, PROT_WRITE|PROT_READ, 
  MAP_SHARED, memfd, base));
char * IM = baseaddr + offset;
*IM = 0x00;
munmap(baseaddr,1);
close(memfd);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM