#Stack Mysteries
6 messages in this thread
Mike,
Your comment on the stack getting overwritten brings up a question I've
got. I just read an explaination of stack frames in one of Kochan's
advanced 'C' books and suddenly stacks make sense. But I doubt I could
explain it to anybody else. Kochan's explaination, I believe, was based on
Intel architecture. How much different are 680×0 frames? And how can I get
the current stack frame pointer within a program. Or better yet with CPR?
Thanks,
—Mike,
68000 and 8086 stack frames are pretty much the same – the registers used
obviously differ, but that's about it. When a function is called,
arguments are pushed in the reverse order (so that the first argument is
pointed to by the stack pointer). The function is then called, which means
the return address is now where the stack pointer points to. Within the
function, automatic variables are then allocated on the stack. This is
done with the link instruction on the 68K. At this point, the frame
register (a5 on the 68K) is setup so that a5+4 points to the 1st argument
to the function, and negative offsets from a5 point to local variables.
There's no portable way to figure out the contents of the stack frame
register in C – however, taking the address of the top-most local variable
can usually give you an indication. From within a debugger, simply look at
the A5 register.
-Mike
Oh, forgot about exit and cleanup. At the end of the function, an unlnk
instruction is done, which de-allocates the stack space reserved for local
variables (actually, the stack pointer is just incremented by the
appropriate amount), a5 is restored to its previous value, and a return is
executed. The caller of the function then increments the stack pointer to
get rid of the arguments it pushed on the stack.
Note that both the Lattice and Manx compilers can generate code which has
no stack frame (for instance, if all local variables are registerized, or
if there are no local variables).
Oops, minor mistake in the previous message….since the link instruction
saves A5 first, the first argument to the function will be at A5+8, not
A5+4.
-Mike
Thanks, Mike. I'll play around with looking at values around the stack
pointer and see what I find. But I sure don't want to tinker with these
things, it's just good information to know.
—Mike,
Just wanted to add that C compilers are free to allocate local variables on
the stack in any order they choose. Some C compilers push in the order
that they are declared while others push in reverse order.
— Mike Roth
This is true. However, almost all C compilers push in reverse order –
doing it the other way makes it very difficult to get variable-parameter
mechanisms working.
-Mike