Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 884
Aditya Avatar asked Oct 26 '25 14:10

Aditya


2 Answers

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
like image 159
Adrian Kiesthardt Avatar answered Oct 29 '25 04:10

Adrian Kiesthardt


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 */
like image 38
Achal Avatar answered Oct 29 '25 05:10

Achal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!