Explicitly assign or access values to or from specific address/location in memory?

前端 未结 3 1883
礼貌的吻别
礼貌的吻别 2021-01-16 07:03

My exact question is that there is any provision in c and c++ to assign a value explicitly to particular address for example suppose I want to stor

3条回答
  •  甜味超标
    2021-01-16 07:47

    You can do it like this:

    *(int *)0x1846010 = 20;  // store int value 20 at address 0x1846010
    

    Retrieving works similar:

    int x = *(int *)0x1846010;
    

    Note that this assumes that address 0x1846010 is writable - in most cases this will generate an exception like Access violation writing location 0x01846010.

    P.S. For your interest, you can check given address writable or not at run-time by using the following (borrowed from here):

    #include 
    #include 
    
    int is_writeable(void *p)
    {
        int fd = open("/dev/zero", O_RDONLY);
        int writeable;
    
        if (fd < 0)
            return -1; /* Should not happen */
    
        writeable = read(fd, p, 1) == 1;
        close(fd);
    
        return writeable;
    }
    

    As discussed here, typically you will only ever do this kind of thing for embedded code etc where there is no OS and you need to write to specific memory locations such as registers, I/O ports or special types of memory (e.g. NVRAM).

提交回复
热议问题