How to retrieving variable value in C++ if you know the variable address

前端 未结 5 1683
别那么骄傲
别那么骄傲 2021-01-23 05:50

Greetings,

I have recently started to code in C++ and have come across a problem to which I was unable to find the answer, so I thought maybe somebody e

相关标签:
5条回答
  • 2021-01-23 06:00

    On today operating systems, the programs handle virtual addresses, not physical ones. Shortly, a specific address for one programs will not point to the same physical location for other programs.

    To do what you want on modern operating systems, you can, for instance, set up a shared memory location.

    But there is a lot of easier way to pass a value from one program to another.

    If you are just wondering that out of curiosity, that's a good question, you can look at what "virtual memory" is.

    0 讨论(0)
  • 2021-01-23 06:12

    It is possible, but it is OS-specific (there is no common C support for it). In general, your second program needs to have the permission that debugger has, and use the same kind of OS calls that a debugger uses.

    0 讨论(0)
  • 2021-01-23 06:13

    On most modern general-purpose OSes (Windows, Linux, etc), you cannot do that. Different programs run in different processes, and each process has its very own memory space. Address 0x7fff5fbff758 in one probably points to a very different place in RAM than address 0x7fff5fbff758 in another (if that address even exists in the other).

    This is why modern OSes have interprocess communications mechanisims, like pipes, shared memory, COM, etc.

    0 讨论(0)
  • 2021-01-23 06:17

    Edit: This obsolete, because the question has changed.

    If you know the type of the variable, its possible.

    For an int variable, you need to insert lines like

    int* addr = (int*)0x7fff5fbff758;
    std::cout << *addr << std::endl;
    

    somewhere in the affected program.

    Accessing the variable from a different program is generally not easily done in a modern operating system, each process has it's own address space so the same address in different processes may map to different physical memory location.

    It depends on the OS, for example in linux you need to trace a process if you want to do it from a different process, see man ptrace. You can read the data in this case with PTRACE_PEEKDATA.

    0 讨论(0)
  • 2021-01-23 06:19

    C++ has no comment on this, one way or the other. It depends entirely on the platform on which your program is running. If you're using Windows, for example, you can use the ReadProcessMemory() function to read the memory of another process (assuming you have adequate permissions).

    Note that modern operating systems are designed to protect processes from interfering with each other. One of the ways they do this is by giving each process its own address space. Processes can't access memory outside this space without using special APIs.

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