1

I would like to know if it is possible to in the first C program:

  1. Allocate and declare an int to the value of 5 in memory
  2. Print out the address of the variable (eg: 0x7ffee6a98ad8)
  3. Terminate

And then in a second C program, after the first has completely finished executing:

  1. Read in the data that was previously declared at address 0x7ffee6a98ad8
  2. Print the correct value of 5

Is this a possibility in C?

If so, how would one go about accomplishing such a task?

I am using Linux, if that matters.

  • 1
    Yes, but only if you run your program on an OS that doesn't clear memory between processes, like DOS (and Windows 3.x?) – Dai Dec 16 '21 at 04:17
  • Note that memory addresses are virtualized. There's no guarantee that the same pointer value from two different processes will reference the same physical location in RAM. – paddy Dec 16 '21 at 04:28
  • @paddy That isn't in the C specification. – Dai Dec 16 '21 at 04:30
  • @Dai - Of course it isn't. The C specification doesn't say anything about that kind of thing ... except possibly when it mentions that the behavior of accessing uninitialized memory is unspecified. – Stephen C Dec 16 '21 at 04:33
  • I was speaking from a system perspective: [Difference between logical and physical addresses](https://stackoverflow.com/q/3697729/1553090) – paddy Dec 16 '21 at 04:36
  • Something like this can be done by creating named shared memory segments. – Eric Postpischil Dec 16 '21 at 10:39

1 Answers1

1

It once was possible. If you made a large C program in DOS and alllocated some RAM with malloc() you could in fact save that address somewhere (like on disk) and start another C program and read that memory.

I hear it's still possible on deeply embedded platforms, but on modern multi-user operating systems, when you allocate RAM from the OS it clears the RAM first so you can't see it.

Question edited to say Linux. Well no, but also yes. Open up the shell process with ptrace(), allocate some memory in the shell process and write to it, and the next program can find it there. This is nothing like wild pointer games, and is really quite tricky. https://techryptic.github.io/2018/04/07/Using-PTRACE-to-Inspect-&-Alter-Memory/ The window is closing; they're starting to tighten things so you can't debug any processes but your own child processes because they don't want a sudo disaster.

Joshua
  • 40,822
  • 8
  • 72
  • 132