Read and write to a memory location

2020-03-04 02:36发布

After doing lot of research in Google, I found below program

#include <stdio.h>

int main()
{
    int val;
    char *a = (char*) 0x1000;
    *a = 20;
    val = *a;
    printf("%d", val);
}

But it is throwing a run time error, at *a = 20.

Then how can I write and read a specific memory location?

Please help me

标签: c codeblocks
9条回答
淡お忘
2楼-- · 2020-03-04 03:28

If you are running your code in user space(which you are), then all the addresses you get are virtual addresses and not physical addresses. You cannot just assume and write to any virtual address.
In fact with virtual memory model you cannot just assume any address to be a valid address.It is up to the memory manager to return valid addresses to the compiler implementation which the handles it to your user program and not the other way round.

In order that your program be able to write to an address:

  1. It should be a valid virtual address
  2. It should accessible to the address space of your program
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-03-04 03:28

Issue of permission, the OS will protect memory space from random access.

You didn't specify the exact error, but my guess is you are getting a "segmentation fault" which would clearly indicate a memory access violation.

查看更多
干净又极端
4楼-- · 2020-03-04 03:30

That is the correct way to write data to memory location 0x1000. But in this day and age of virtual memory, you almost never know the actual memory location you want to write to in advance, so this type of thing is never used.

If you can tell us the actual problem you're trying to solve with this, maybe we can help.

查看更多
登录 后发表回答