Two Different Values At the Same Memory Address

Two different values at the same memory address

Why are there two different datas at the same address?

There aren't. The compiler is allowed to optimize any mention of a const to be as though you had written its compile-time value in there.

Note that the compiler is also allowed to generate code that erases your hard disk when you run it if you do nasty tricks like writing to memory reserved for consts.

Pointer with same memory address with different value

double d = 2.5;
auto p = (int*)&d;
auto q = &d;

p and q are created pointing to the same memory location. The memory holds a double (usually 8 bytes)

When you create

auto p = (int*)&d;

you are telling the compiler ( reintepret_cast< int*> ( &d) ) that the value in d was an integer.

So the values of the pointers are the same, but the types are not.

When you print out

cout<<*q<<endl; // prints 2.5

You are displaying the correct value - as it came in and out through that.

when you print out

cout<<*p<<endl; //prints 0

You are looking at 4 (typically) bytes of the 8 byte memory, and interpreting them as an integer.

These happen to be 0x00, 0x00, 0x00, 0x00

Two different values at the same memory address - assembly

I made an understandable mistake. When doing:

mov [operand1], eax
PRINT_STRING "[operand1] is: "
PRINT_HEX 1, [operand1]
NEWLINE

This code prints the first byte of the content (which is the address where my actual big number begins) contained at the address where this local variable (operand1) resides. In order to get the actual value which resides at [operand1] I had to do this:

mov ebx, [operand1]
PRINT_STRING "[operand1] is: "
PRINT_HEX 1, [ebx]
NEWLINE

Why the same memory location holding different values at the same time?

You've got undefined behavior, so anything can happen. In this case, the compiler knows that i cannot change value, and probably just uses the value directly.

Pointers pointing to same memory location but different program

In modern operating systems like linux, windows or MacOs each process has its own virtual memory address space.
Therefore the memory address from the process of your program p1 has nothing to do with the memory of the process of your program p2.

If you really want to access memory between processes directly you need to use shared memory.

But what is your intention? Do you just want to play around, or do you want communication between processes? In the later case you should read about IPC - inter process communication. There are a lot of IPC mechanisms you can use like named pipes, sockets or shared memory, depending on what you want to achieve.

You may have a look at this article for first introduction into the topic: https://en.wikipedia.org/wiki/Inter-process_communication



Related Topics



Leave a reply



Submit