Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is heap memory per-process? (or) Common memory location shared by different processes?

Every process can use heap memory to store and share data within the process. We have a rule in programming whenever we take some space in heap memory, we need to release it once job is done, else it leads to memory leaks.

int *pIntPtr = new int;
.
.
.
delete pIntPtr;

My question: Is heap memory per-process?

If YES,

then memory leak is possible only when a process is in running state.

If NO,

then it means OS is able to retain data in a memory somewhere. If so, is there a way to access this memory by another process. Also this may become a way for inter-process communication.

I suppose answer to my question is YES. Please provide your valuable feedback.

like image 796
Akaanthan Ccoder Avatar asked Jun 30 '10 06:06

Akaanthan Ccoder


2 Answers

On almost every system currently in use, heap memory is per-process. On older systems without protected memory, heap memory was system-wide. (In a nutshell, that's what protected memory does: it makes your heap and stack private to your process.)

So in your example code on any modern system, if the process terminates before delete pIntPtr is called, pIntPtr will still be freed (though its destructor, not that an int has one, would not be called.)

Note that protected memory is an implementation detail, not a feature of the C++ or C standards. A system is free to share memory between processes (modern systems just don't because it's a good way to get your butt handed to you by an attacker.)

like image 180
Jonathan Grynspan Avatar answered Oct 21 '22 23:10

Jonathan Grynspan


In most modern operating systems each process has its own heap that is accessible by that process only and is reclaimed once the process terminates - that "private" heap is usually used by new. Also there might be a global heap (look at Win32 GlobalAlloc() family functions for example) which is shared between processes, persists for the system runtime and indeed can be used for interprocess communications.

like image 25
sharptooth Avatar answered Oct 21 '22 22:10

sharptooth