You can't access the memory like this (at-least in a complex system like your PC/Laptop).
This is because the addresses you see in one program(process) aren't the real addresses. They are the Virtual Addresses
and they are quite different from the Real Addresses
.
Let me try to define three notions for you:
- Physical Address: The address of where something is physically located in the RAM chip (Main Memory).
- Logical/Virtual Address: The address that your program uses to reach its things. It's typically converted to a physical address later by a hardware chip(
MMU
) (mostly, not even the CPU is aware really of this conversion).
- MMU: A memory management unit (MMU), sometimes called paged memory management unit (PMMU), is a computer hardware unit having all memory references passed through itself, primarily performing the translation of virtual memory addresses to physical addresses. Read more about it over here.
For a simple system(which doesn't have MMU
), physical address = virtual address. Larger systems are generally demand-paged virtual memory systems, where the MMU
translates a virtual address to a physical address, or alerts the OS to take action (to allocate a page, read a page from disk, or deny access to a page -> trap or fault). Typically, an operating system assigns each program its own virtual address space
In your case, both the programs have different virtual memory address space. You can't refer anything in one program belonging to another program(process). This is due to the fact that you wouldn't get the real address if you try to get the address of a variable in one of your program. The addresses you will get have validity in your current program and wouldn't make any sense if you try to use addresses of a program into another program(process).
So, what you were trying to do will result into UNDEFINED BEHAVIOR
. In your case, it has resulted into Segmentation Fault
as the address you were trying to deference, didn't exit in virtual address space of your program. Although there are several techniques which can be used to achieve what you want. Inter-process communication
is the term used for communication techniques between two processes. Few are given below which can be used in a POSIX
system for inter-process communication:
- Pipe
- Message Queue
- Sockets
- Memory-Mapped
- Shared Memory
Read more about virtual and physical address over here.