Obviously Wikipedia has a fair amount of information on the topic, but I wanted to make sure I understand. And from what I can tell it's important to understand the stack/heap relationship to really understand a memory leak?
So here's what I (think) I understand. Corrections are very welcome!
When you first start your program, a block of memory is allocated, say 0x000 to 0xFFF. The first part (say 0x000 to 0x011) is the code/text segment where the program code is loaded.
+--------------+ 0x011
| Program Code |
+--------------+ 0x000
Then you have the stack (say 0x012 to 0x7ff) that holds local variables, and they are stored/retrieved FIFO. So if you had something like
char middleLetter(string word){
int len = word.length();
return word[len/2];
}
int main(){
int cool_number;
char letter;
letter = middleLetter("Words");
...
Then your variables would be allocated on the stack, which would look like this:
+-------------+ 0x7ff
| |
| |
| |
| ... |
| len |
| letter |
| cool_number |
+-------------+ 0x012
Of course, if you were allocating memory somewhere (using malloc
or new
), but never freeing it, then your heap could look like this, and you now have a memory leak:
+-------------+ 0xfff
| |
| malloc(20) | 0xf64
| malloc(50) | 0xf32
| malloc(50) | 0xf00
| ... |
| |
+-------------+ 0x800
What this means is that while you can directly access 0xf32 with pointer arithmetic, the OS/your program thinks that memory locations 0xf00-0xf46 are already taken, and won't ever use those spots for storage again, until your program is closed and the memory is freed. But what about shared memory? Wikipedia says it won't ever be released (until your computer is restarted?). How do you know if it's shared memory?
Is this a pretty good basic understanding? Is there anything I'm missing/have wrong? Thanks for looking!