Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What goes to RAM, Harddrive, Stack and Heap in C++?

Could someone tell in general what goes to what (Harddrive,RAM, Stack or Heap) at runtime in C++ for these instances :

  • Local/global variables

  • Classes, Methods and functions

  • Pointers

  • Objects

And is Stack/Heap both located in physical RAM?

I would appreciate if someone could include hardware analogy in the answer. Thanks.

like image 297
Maiss Avatar asked Mar 24 '12 18:03

Maiss


2 Answers

All of them go into memory. Now, the definition of "in memory" depends on the operating system, compiler and linker options, the executable format and a million other factors.

On many modern operating systems, when a process is created, the executable file is mapped into memory (this means a memory region was reserved for the executable but doesn't mean the executable has been loaded in that location yet).

Some OSes will load parts of the executable file as it is accessed (see "delay loading"), which is more common for dynamically loaded libraries (DLLs on Windows, and Shared Objects on UNIX-like systems). This mostly influences the current "location" of functions, they are either "on disk" as the executable file, or "in memory" if that part of the executable has been mapped.

Variables and all other program data go to memory. However, any OS that operates with virtual memory may swap all your program's running state (including the stack and heap) to disk at its convenience, and then later restore it back to keep running your program.

In conclusion, all the items on your list (variables, functions, etc.) are in memory, although then may not be stored in "physical RAM" at all times.

like image 140
André Caron Avatar answered Oct 01 '22 03:10

André Caron


This is generally dependent on OS, but it's generally like so:

Everything goes to RAM. The binary resides in the hard-drive, but, when ran, is fully loaded, along with dependent libraries, into RAM.

Stack and heap are implementation details, but they also reside in the RAM.

Although loaded in RAM, the memory is not directly addressable. The operating system allocates virtual memory for each process. This means that the address 0x001 is not actually located at 0x001 in the RAM, but represents an address in virtual address space.

EDIT: Clarification to one of op's comments:

Are binaries fully or partially loaded at runtime? And, are those binaries only accessed once at runtime or continuisly being read from Harddrive?

For example, in MS, if you link against a library, it will be fully loaded at runtime, at the start of the program. If you load it programatically, via LoadLibrary(), it is loaded into memory at the function call, and can be unloaded from memory.

like image 22
Luchian Grigore Avatar answered Oct 01 '22 02:10

Luchian Grigore