See this page as a slide show
CS253 Memory Segments
Segments
- There are several “segments”, or areas of memory, where parts
of your program live, in a typical computer architecture:
- Text: executable code
- Data: initialized static data
- BSS: uninitialized static data
- Stack: local variables
- Heap: allocated via
malloc(
 )
or new
Text: executable code
- The text segment contains executable code.
- It is typically read-only at run-time.
- It can be shared—if several users are running
bash
, then we only
need one copy of bash’s executable code in RAM.
This saves memory and and increases the chance of instructions being in cache.
- The text segment is stored in the
a.out
file.
Data: initialized static data
- The data segment contains initialized static data.
- It is read-write at run-time—programs may alter their variables.
- The data segment is stored in the
a.out
file.
BSS: uninitialized static data
- The bss segment contains uninitialized static data.
- It is zero-initialized at initial load of the program.
- It is read-write at run-time—programs may alter their variables.
- Since bss has no data associated with it, the
a.out
file
just has to know how big the bss segment is, lay out that much
space at run-time, and clear it. Almost no space required in
the a.out
file.
- The origin of the name is unclear. It may have been an old assembly
pseudo-op for Begin Section started by Symbol.
Stack: local variables
- The stack segment is contains uninitialized local variables.
- It is read-write at run-time—programs may alter their local variables.
- It is not stored in the
a.out
at all, except implicitly,
in subroutine preamble code.
Heap: allocated via new
- The heap segment is contains uninitialized dynamic variables.
- It is read-write at run-time—programs may alter their local variables.
- It is not stored in the
a.out
at all.
- Traditionally, free/allocated dynamic memory is kept track of via
a “heap” data structure, hence the name.
Example
int a, b=45;
const int c = 299'792'458;
int main() {
static double d, e = 2.7182818284590452353;
long *f = new long[10];
vector<int> g = {123,456,789};
cout << "&exit: " << (void *) &exit << "\n"
"&c: " << &c << "\n\n"
"&b: " << &b << "\n"
"&e: " << &e << "\n"
"&cout: " << &cout << "\n\n"
"&a: " << &a << "\n"
"&d: " << &d << "\n\n"
"&f[0]: " << &f[0] << "\n"
"&g[0]: " << &g[0] << "\n\n"
"&g: " << &g << "\n"
"&f: " << &f << "\n";
delete[] f;
}
&exit: 0x400950
&c: 0x401518
&b: 0x603090
&e: 0x603098
&cout: 0x6030a0
&a: 0x6031b8
&d: 0x6031c0
&f[0]: 0x16072b0
&g[0]: 0x1607310
&g: 0x7ffc0d449550
&f: 0x7ffc0d449570