The nice thing about C is that it allows you to peer into the machine using printf and the %p specifier to output hexadecimal addresses of variables and the like. In this post we’ll look briefly at how the four segments of memory are represented. (The entire program is at the end of the post).
Initialized Data Segment
More commonly called the data segment,which contains global variables and initialized static variables. For example, global variables (outside main):
int globalVar = 24; char globalStr[] = "global string"; const char *strlit = "string literal";
in addition to localized static variables (inside main):
static int staticVar = 12;
If the hexadecimal addresses are output:
INITIALIZED DATA SEGMENT global variable: 24 at 0x105e75038 global string: global string at 0x105e7503c string literal: string literal at 0x105e74db8 static variable: 12 at 0x105e75058
Now let’s look at the memory a little closer (with HEX converted to decimal).
INITIALIZED DATA SEGMENT globalVar: size=4 memory position=4394012728 globalStr: size=14 memory position=4394012732 strlit: size=8 memory position=4394012088 staticVar: size=4 memory position=4394012760
The first global variable, globalVar, is stored at position 4394012728, which at 4 bytes in size takes us to the start position of the global string, globalStr. The string literal, strlit, is 8 bytes in length ( on a 64-but machine), and signifies a pointer. The global character array globalStr starts at 4394012732, and is 14 bytes in length (13 + 1 for ‘\0’).
Note that the data segment can be further classified into initialized read-only, and initialized read-write regions. The variables globalvar, globalStr, and staticVar are stored in the read-write region. In the case of strlit, the string literal, “string literal” is stored in the read-only region, and the character pointer variable strlit is stored in the read-write region.
UNInitialized Data Segment
The uninitialized data segment, often called the BSS (block started by symbol.), contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code. A global variable (outside main) with no initial value can be created in the following context:
int globalVarUninit;
This is stored in the uninitialized data segment in the following manner:
UNINITIALIZED DATA SEGMENT uninitialized global: 0 at 0x105e7505c
Now let’s look at the memory a little closer (with HEX converted to decimal).
UNINITIALIZED DATA SEGMENT globalVarUninit: size=4 memory position=4394012764
Notice that the memory location is after the last memory position in the initialized data segment.