Pointers and local variables are stored on the stack.
Global variables are declared on the heap. I got that, understood. Use of * and & are understood as much as someone can for a 3 day knowledge of them. When you want to declare a variable on the heap, you must declare a pointer, and call the function "new"... Ok, I got that.
My question is how do you know WHEN you need to do this? Why not just declare a global variable? The books I have explain how to do it, but they don't explain why you would, or how to know when you need to. Any opinions would be welcome, and thank you in advance.
Globals are not stored in the heap. http://en.wikipedia.org/wiki/Data_segment you can see the heap is a part of the data segment. Also, pointers are variables, they follow the same rules: a pointer defined inside a function goes in the stack (what it points to may or may not).
Global variables serve a very different purpose from dynamic memory allocation.
The former changes how the program sees and exchanges data, the latter changes, at runtime, how much memory the program is allowed to use.
I can name two situations where you need dynamic allocation, though I can't say if they're the only ones.
- When you need to store something bigger than the memory you can spare in the stack
- When you don't know, at compile time, how much memory you need to store something (e.g. a string the user inputs)
Global variables do not have much control on who does access them.
1 2 3 4 5 6 7 8 9 10
gaz = 7;
// Q: What is the value of gaz now?
// A: No idea. bar() could modify global variables.
Besides, tracking the lifetime of a global is daunting.
1 2 3
foo is a variable. Could be local, global, or in heap. What we do know for certain is that foo holds an integer value 7 and that the value is in heap, yet we did not call new explicitly, nor do we need to explicitly delete it either.
Use local variables on the stack when the lifetime of the variable can be defined by the scope, i.e. when the current scope ends, the variable is destroyed.
Use dynamically allocated memory on the heap when you need to control the lifetime of that variable yourself, independently of the current scope. You decide when to delete the variable and free up the memory.
Use global variables NEVER. They are almost always a bad idea, and should be avoided.