Home > Software engineering >  does the value I did allocate to an adress inside the memory stay?
does the value I did allocate to an adress inside the memory stay?

Time:11-05

lets say I initialized a value (ex 10) to a variable A in c after that I ended my program and coded another program, in that program I declared a variable B and by a miracle it was allocated at the same address of the variable A that I located in my first program so, does the value of the first variable (A) will be given to the second one (B) if i didn't initialize a value to it?

I tried to use the cstdint library to get the located value of a specific address but when I tried to do that I got a segmentation fault.

my code :

#include <cstdint>
int main()
{
uintptr_t p = 0x0001FBDC;
int value = *reinterpret_cast<int *>(p);
}

CodePudding user response:

Firstly, your process is almost certainly working with virtual memory addresses. That means the address 0x0001FBDC does not necessarily refer to the same physical memory across runs (or even during a single run).

Ignoring that, in general, your program has to share the same physical memory with all other applications (not at the same time, but obviously the system memory is reused by all processes). But your program might have left sensitive data in memory and letting other programs access that would be a security concern.

For that reason, in general, once your program is closed and some other program wants to use the same memory, the operating system zeros-out the section and only then hands it out to other programs. This also has the nice consequence that global variables are zero-initialized cheaply for you (which is a mandated standard behavior).

So, no, you can't access the same variable across runs. Some operating systems will allow you to allocate memory and share across processes, so you might want to look into that.

But, of course, none of this is guaranteed to happen. You might be running your program on an embedded system with no OS or memory protection, and then you might observe that a particular address that is not overwritten by anything else (other programs, other functions in your program, etc.) keeps its value.

  • Related