I read that the dynamic link points to the previous activation record ( aka a "stack frame"), so it makes sense in dynamic scoped programming language. But in static scoped programming language, why the access link (which points to activation record of function in one lower nesting level) isn't enough? And specifically in C - why access link is not needed? And why dynamic link is needed?
I will use this nomenclature which is more familiar to me:
Activation record: Stack frame
Dynamic link: [saved] frame pointer
So, I interpret your question as: Why are frame pointers needed?[1]
A frame pointer is not required.
Some compilers (e.g. Green Hills C++, GCC with -O2) don’t usually generate one or can be asked not to generate it (MSVC, GCC).
That said, it does of course have its benefits:
Easy traversing of the call stack: generating a stack trace is as easy as traversing a linked list where the frame pointer forms the head. Makes implementing stack traces and debuggers much easier.
Easier code generation: stack variables can be referenced by indexing the frame pointer instead of the all-the-time-changing stack pointer. The stack pointer changes with each push/pop, the frame pointer stays constant within a function (between the prologue/epilogue)
Should things go awry, stack unwinding can be done using the frame pointer. This is how Borland’s structured exception handling (SEH) works.
Streamlines stack management: Particularly implementations of setjmp(3)
, alloca(3)
and C99-VLA may (and usually do) depend on it.
Drawbacks:
But as you noticed, a compiler can generate perfectly fine code without having to maintain a frame pointer.
[1] If that's not what's meant, please elaborate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With