- Instance variables and Objects lie on Heap. Remember this is where the state is maintained and when you get memory leaks this is where your profiler helps you to find the allocation of memory.
- Local variables and methods lie on the Stack. So if we have a main method which calls the go() method which calls the gone() method then the stack from top to bottom would consist of
Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).
A typical C program was laid out flat in memory with an opportunity to increase by changing the brk() value. Typically, the HEAP was just below this brk value and increasing brk increased the amount of available heap.
The single STACK was typically an area below HEAP which was a tract of memory containing nothing of value until the top of the next fixed block of memory. This next block was often CODE which could be overwritten by stack data in one of the famous hacks of its era.
One typical memory block was BSS (a block of zero values) which was accidentally not zeroed in one manufacturer's offering. Another was DATA containing initialized values, including strings and numbers. A third was CODE containing CRT (C runtime), main, functions, and libraries.
#include
int
main(
void
)
{
return
0;
}
$ gcc memory-layout.c -o memory-layout $ size memory-layout text data bss dec hex filename 960 248 8 1216 4c0 memory-layout
2. Let us add one global variable in program, now check the size of bss (highlighted in red color).
int global; /* Uninitialized variable stored in bss*/ |
$ gcc memory-layout.c -o memory-layout
$ size memory-layout
text data bss dec hex filename
960 248 12 1220 4c4 memory-layout
3. Let us add one static variable which is also stored in bss.
int global; /* Uninitialized variable stored in bss*/ int main( void ) { static int i; /* Uninitialized static variable stored in bss */ return 0; } |
$ size memory-layout
text data bss dec hex filename
960 248 16 1224 4c8 memory-layout
4. Let us initialize the static and global variable which will then be stored in Data Segment (DS)
$ gcc memory-layout.c -o memory-layout
int global = 10; /* initialized global variable stored in DS*/ |
int main( void ) { static int i = 100; /* Initialized static variable stored in DS*/ return 0; } |
$ size memory-layout
text data bss dec hex filename
960 256 8 1224 4c8 memory-layout
No comments:
Post a Comment