Read and write to a memory location

前端 未结 9 1247
忘掉有多难
忘掉有多难 2021-01-05 05:40

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

#include 

int main()
{
    int val;
    char *a = (char*) 0x1000;
          


        
相关标签:
9条回答
  • 2021-01-05 06:05

    You can't just write at any random address. You can only modify the contents of memory where your program can write.

    If you need to modify contents of some variable, thats why pointers are for.

    char a = 'x';
    char* ptr = &a; // stored at some 0x....
    *ptr = 'b'; // you just wrote at 0x....
    
    0 讨论(0)
  • 2021-01-05 06:07

    You cannot randomly pick a memory location and write to. The memory location must be allocated to you and must be writable.

    Generally speaking, you can get the reference/address of a variable with & and write data on it. Or you can use malloc() to ask for space on heap to write data to.

    This answer only covers how to write and read data on memory. But I don't cover how to do it in the correct way, so that the program functions normally. Other answer probably covers this better than mine.

    0 讨论(0)
  • 2021-01-05 06:09

    This is throwing a segment violation (SEGFAULT), as it should, as you don't know what is put in that address. Most likely, that is kernel space, and the hosting environment doesn't want you willy-nilly writing to another application's memory. You should only ever write to memory that you KNOW your program has access to, or you will have inexplicable crashes at runtime.

    0 讨论(0)
  • 2021-01-05 06:10

    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.

    0 讨论(0)
  • 2021-01-05 06:14

    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
    0 讨论(0)
  • 2021-01-05 06:18

    First you need to be sure about memory location where you want to write into. Then, check if you have enough permission to write or not.

    0 讨论(0)
提交回复
热议问题