By convention, we express these addresses in base 16 numbers. For instance, the smallest possible address is 0x00000000 (where the 0x means base 16), and the largest possible address could be 0xFFFFFFFF.
persists throughout the entire life of the program, and is used to store things like global variables, or variables created with the static clause. For example:
int theforce;
The memory to store this variable can come from one of two places:
static int theforce;
The stack segment is near the top of memory with high address. Every time a function is called, the machine allocates some stack memory for it. When a new local variables is declared, more stack memory is allocated for that function to store the variable. Such allocations make the stack grow downwards. After the function returns, the stack memory of this function is deallocated, which means all local variables become invalid. The allocation and deallocation for stack memory is automatically done.
Example: Different variables are put on the stack as a function of their occurrence in main and subfunctions.
There is a limit on the size of the stack which can vary with the operating system (e.g. OSX currently has a default stack size of 8MB). If a program puts too much information on the stack, the stack overflows. Stack overflow happens when all the memory in the stack has been allocated. Further allocations begin overflowing into other sections of memory.
A summary of the stack:
Pirate techniques on the stack:
The heap is a large pool of memory that can be used dynamically (i.e. 'free storage'). This is memory that is not automatically managed; the programmer has to explicitly allocate (using functions such as malloc), and deallocate (e.g. free) the memory. Unlike the stack, there are generally no restrictions on the size of the heap, other than the physical size of memory in the machine. Variables created on the heap are accessible anywhere in the program. Most importantly, heap memory requires the programmers to use pointers!.
A summary of the heap:
Check out the Example code here
#include <stdio.h>
#include <stdlib.h>
int x;
int main(void){
int y;
char *str;
y = 4;
printf("stack memory: %d\n", y);
str = malloc(100*sizeof(char));
str[0] = 'm';
printf("heap memory: %c\n", str[0]);
free(str);
return 0;
}
The variable x is static storage, because of its global nature. Both y and str are dynamic stack storage which is deallocated when the program ends. The function malloc is used to allocate 100 pieces of of dynamic heap storage, each the size of char, to str. Conversely, the function free, deallocates the memory associated with str.