Quote:Original post by redirectionkid
Okay, I think I have a better idea of things. However I'm not quite sure here:Quote:Original post by Spoonbender
Every new function pushes data onto the stack, and when the function ends, they're popped off, leaving the stack as it looked before the function was called.
Do all variables within the function utilize the stack by default? If so, how could one access a variable that is defined before another variable, without "popping off" the previous variable, and losing that data?
Well, that's where the similarity to a real-world stack ends. On a computer, it's just a bunch of memory addresses. If you have the address of something halfway down the stack, then you can manipulate it. The stack is just a method to be able to keep adding and removing data, always in a "first in-last out" order.
If a function is called with the address of another variable on the stack, then it won't be on top of the stack, but you have the address, so you can still read it or change its value.
On the other hand, when a function ends, all its data is popped off the stack, meaning that if you still have the address of a function variable (maybe you returned the address of a local variable?), then suddenly that points to nothing, to a semi-random value that's going to be overwritten as soon as someone push data onto the stack.
That's why you use 'new' to allocate memory. When you use new, you create a variable on the heap. It stays there until it's deleted.
When you just do something like this:
int x = 42;
it's created on the stack, and once the function ends, poof, the variable is gone.
Make sense? :P
Or to put it in code, imagine you call a function like this one:
int* foo(int* a){ // Now a points to something further down the stack (or maybe on the heap). // If it's on the stack, it won't be popped off until the function it exists // in ends, so it's safe enough to use here. // Create a local variable and return the address of it. // Of course, this goes out of scope when the function ends, so returning // the address of it is *very* stupid. What happens is that when the function // ends, it pops all the local variables (the ones created in this function // without using 'new') off the stack, and suddenly, &b points to nothing in // particular. It'll get overwritten any moment. int b = 1; return &b;}