The memory layout of a computer program and how a computer works.

A computer program that is loaded into a computer's RAM has a distinct layout. Before we dive into how a computer program looks in memory we need to understand what is the computer offering us when it comes to memory management.

A computer's RAM memory is a long array of bits. Instead of reading and writing 1 bit at a time we read and write in chunks of 8 bits called bytes. If we want to read or write a location we need to know it's address. If our computer supports 32 bit addresses than we can work with:

 2^32 = 4294967296 bytes which is 4294967296/1024=4194304 Kilo Bytes, which is 4194304/1024= 4096 Mega Bytes which is 4 Giga Bytes.

Adresses start at 0 and go all the way to 2^32-1.

You can think of a RAM memory as a long string of beads, each bead containing 8 bits.

A computer program is composed out of data and instructions.
Instructions tell the CPU what to do with data from memory. The only operations that a CPU does to data are mathematical/logical operations and moving data around memory operations.
 Instructions and data are loaded into memory in segments. There are different segments for data and instructions. Segments as the name tells are just pieces of continuous memory that the central processing unit keeps tracks of. The CPU can discern between data segments and code segments.

When a program is loaded into memory, its data segment and code segment are loaded. Also there are other segments initialized. One is the stack data segment and the other is the heap data segment.

We have stack segment because programs are organized into functions that generate intermediate data when executed. That intermediate data lives from function execution beginning to function end, when the function finishes executing the intermediate data is deleted/erased.  So we need a place to store that intermediate function data, the stack segment. The heap segment is for data that we compute when the program runs and we want to keep in between function calls. That data is erased when the program finishes executing.

What I've described above is a short description of how a CPU interacts with memory and how  a program looks when it's loaded in memory. There a lot more details the most important being CPU registers. A picture is worth a million words, so look at this one:

c program computer memory layout

No comments :

Post a Comment