C Variable Preserved on Stack After Running Program Again
In calculator scientific discipline, a call stack is a stack information structure that stores information about the active subroutines of a computer programme. This kind of stack is likewise known as an execution stack, program stack, command stack, run-time stack, or machine stack, and is often shortened to just "the stack". Although maintenance of the call stack is important for the proper performance of virtually software, the details are usually hidden and automatic in high-level programming languages. Many computer educational activity sets provide special instructions for manipulating stacks.
A call stack is used for several related purposes, but the main reason for having one is to go on track of the point to which each active subroutine should return control when it finishes executing. An agile subroutine is i that has been called, but is all the same to consummate execution, after which control should be handed back to the point of call. Such activations of subroutines may be nested to whatsoever level (recursive as a special case), hence the stack structure. For example, if a subroutine DrawSquare
calls a subroutine DrawLine
from four different places, DrawLine
must know where to return when its execution completes. To achieve this, the accost following the instruction that jumps to DrawLine
, the return address, is pushed onto the top of the telephone call stack with each call.
Clarification [edit]
Since the call stack is organized as a stack, the caller pushes the return address onto the stack, and the called subroutine, when information technology finishes, pulls or pops the render address off the call stack and transfers control to that address. If a called subroutine calls on still another subroutine, it will push button some other render address onto the call stack, and then on, with the information stacking upwards and unstacking as the program dictates. If the pushing consumes all of the space allocated for the call stack, an error called a stack overflow occurs, mostly causing the programme to crash. Adding a subroutine's entry to the call stack is sometimes called "winding"; conversely, removing entries is "unwinding".
There is usually exactly one call stack associated with a running program (or more accurately, with each task or thread of a process), although boosted stacks may be created for signal treatment or cooperative multitasking (as with setcontext). Since there is merely one in this important context, it can exist referred to every bit the stack (implicitly, "of the task"); however, in the Forth programming language the data stack or parameter stack is accessed more explicitly than the call stack and is unremarkably referred to as the stack (see below).
In high-level programming languages, the specifics of the telephone call stack are usually hidden from the programmer. They are given admission only to a prepare of functions, and non the retention on the stack itself. This is an instance of abstraction. Most assembly languages, on the other hand, crave programmers to be involved with manipulating the stack. The bodily details of the stack in a programming linguistic communication depend upon the compiler, operating system, and the available instruction set.
Functions of the telephone call stack [edit]
As noted in a higher place, the primary purpose of a phone call stack is to store the return addresses. When a subroutine is called, the location (address) of the teaching at which the calling routine can later resume needs to be saved somewhere. Using a stack to save the render address has important advantages over some alternative calling conventions, such as saving the return address before the beginning of the called subroutine or in another fixed location. Ane is that each task can have its own stack, and thus the subroutine can be thread-rubber, that is, can be active simultaneously for different tasks doing dissimilar things. Another do good is that by providing reentrancy, recursion is automatically supported. When a part calls itself recursively, a return address needs to be stored for each activation of the office and so that information technology tin can subsequently be used to return from the function activation. Stack structures provide this adequacy automatically.
Depending on the language, operating system, and auto surround, a call stack may serve additional purposes, including for example:
- Local information storage
- A subroutine oftentimes needs memory infinite for storing the values of local variables, the variables that are known just within the active subroutine and do not retain values later on it returns. It is often convenient to allocate infinite for this use by only moving the elevation of the stack by enough to provide the infinite. This is very fast when compared to dynamic memory allocation, which uses the heap space. Note that each dissever activation of a subroutine gets its own separate space in the stack for locals.
- Parameter passing
- Subroutines oftentimes require that values for parameters be supplied to them by the code which calls them, and it is not uncommon that infinite for these parameters may be laid out in the call stack. Generally if there are merely a few small-scale parameters, processor registers will exist used to laissez passer the values, but if there are more than parameters than can be handled this style, memory infinite volition be needed. The call stack works well equally a place for these parameters, peculiarly since each telephone call to a subroutine, which volition have differing values for parameters, will be given separate infinite on the phone call stack for those values.
- Evaluation stack
- Operands for arithmetics or logical operations are nigh often placed into registers and operated on there. Nevertheless, in some situations the operands may be stacked upwards to an arbitrary depth, which means something more than registers must be used (this is the case of register spilling). The stack of such operands, rather like that in an RPN calculator, is called an evaluation stack, and may occupy space in the call stack.
- Pointer to current example
- Some object-oriented languages (e.g., C++), shop the this pointer along with role arguments in the call stack when invoking methods. The this pointer points to the object instance associated with the method to be invoked.
- Enclosing subroutine context
- Some programming languages (east.m., Pascal and Ada) support declaration of nested subroutines, which are allowed to access the context of their enclosing routines, i.e., the parameters and local variables inside the telescopic of the outer routines. Such static nesting can repeat (a function declared within a role alleged within a role…). The implementation must provide a means past which a called office at any given static nesting level tin can reference the enclosing frame at each enclosing nesting level. Commonly this reference is implemented past a pointer to the frame of the nearly recently activated instance of the enclosing role, called a "downstack link" or "static link", to distinguish it from the "dynamic link" that refers to the immediate caller (which need not be the static parent part).
- Instead of a static link, the references to the enclosing static frames may exist collected into an assortment of pointers known as a display which is indexed to locate a desired frame. The depth of a routine'southward lexical nesting is a known constant, so the size of a routine'south display is fixed. Also, the number of containing scopes to traverse is known, the index into the display is as well fixed. Commonly a routine'due south brandish is located in its own stack frame, but the Burroughs B6500 implemented such a display in hardware which supported up to 32 levels of static nesting.
- The display entries denoting containing scopes are obtained from the appropriate prefix of the caller's display. An inner routine which recurses creates separate telephone call frames for each invocation. In this case, all of the inner routine'southward static links bespeak to the same outer routine context.
- Other return state
- Beside the return address, in some environments there may exist other machine or software states that need to be restored when a subroutine returns. This might include things like privilege level, exception-treatment information, arithmetic modes, and so on. If needed, this may be stored in the phone call stack just as the return address is.
The typical call stack is used for the render address, locals, and parameters (known as a phone call frame). In some environments there may be more or fewer functions assigned to the call stack. In the Forth programming language, for example, ordinarily only the return address, counted loop parameters and indexes, and possibly local variables are stored on the telephone call stack (which in that environment is named the render stack), although any data tin can be temporarily placed there using special render-stack treatment code and so long equally the needs of calls and returns are respected; parameters are ordinarily stored on a split data stack or parameter stack, typically called the stack in Forth terminology even though in that location is a call stack since it is commonly accessed more explicitly. Some Forths likewise have a third stack for floating-bespeak parameters.
Structure [edit]
A call stack is composed of stack frames (likewise called activation records or activation frames). These are auto dependent and ABI-dependent data structures containing subroutine country information. Each stack frame corresponds to a call to a subroutine which has non notwithstanding terminated with a return. For instance, if a subroutine named DrawLine
is currently running, having been called past a subroutine DrawSquare
, the top part of the call stack might be laid out similar in the adjacent flick.
A diagram similar this can be drawn in either direction as long as the placement of the top, and so management of stack growth, is understood. Furthermore, independently of this, architectures differ as to whether call stacks grow towards higher addresses or towards lower addresses. The logic of the diagram is independent of the addressing option.
The stack frame at the top of the stack is for the currently executing routine, which tin can access information within its frame (such as parameters or local variables) in any order.[one] The stack frame usually includes at least the post-obit items (in push order):
- the arguments (parameter values) passed to the routine (if any);
- the return address back to the routine's caller (e.g. in the
DrawLine
stack frame, an address intoDrawSquare
's code); and - space for the local variables of the routine (if any).
Stack and frame pointers [edit]
When stack frame sizes tin can differ, such as betwixt unlike functions or between invocations of a item part, popping a frame off the stack does not constitute a stock-still decrement of the stack pointer. At function return, the stack pointer is instead restored to the frame pointer, the value of the stack pointer but before the function was called. Each stack frame contains a stack arrow to the top of the frame immediately below. The stack pointer is a mutable register shared betwixt all invocations. A frame pointer of a given invocation of a part is a copy of the stack arrow as it was before the function was invoked.[2]
The locations of all other fields in the frame can be defined relative either to the meridian of the frame, equally negative offsets of the stack pointer, or relative to the top of the frame below, as positive offsets of the frame arrow. The location of the frame pointer itself must inherently be defined as a negative showtime of the stack pointer.
Storing the address to the caller'due south frame [edit]
In about systems a stack frame has a field to comprise the previous value of the frame pointer register, the value it had while the caller was executing. For example, the stack frame of DrawLine
would accept a retentiveness location property the frame arrow value that DrawSquare
uses (not shown in the diagram above). The value is saved upon entry to the subroutine and restored upon return. Having such a field in a known location in the stack frame enables code to access each frame successively underneath the currently executing routine'south frame, and also allows the routine to easily restore the frame pointer to the caller'south frame, just earlier it returns.
Lexically nested routines [edit]
Programming languages that support nested subroutines also have a field in the call frame that points to the stack frame of the latest activation of the procedure that well-nigh closely encapsulates the callee, i.e. the firsthand scope of the callee. This is called an admission link or static link (as it keeps track of static nesting during dynamic and recursive calls) and provides the routine (every bit well as any other routines it may invoke) access to the local data of its encapsulating routines at every nesting level. Some architectures, compilers, or optimization cases store one link for each enclosing level (not only the immediately enclosing), so that deeply nested routines that admission shallow data do not take to traverse several links; this strategy is often called a "display".[3]
Access links can be optimized away when an inner role does non access whatever (non-abiding) local data in the encapsulation, as is the case with pure functions communicating only via arguments and return values, for example. Some historical computers, such as the Burroughs large systems, had special "display registers" to back up nested functions, while compilers for almost modernistic machines (such as the ubiquitous x86) but reserve a few words on the stack for the pointers, as needed.
Overlap [edit]
For some purposes, the stack frame of a subroutine and that of its caller can be considered to overlap, the overlap consisting of the area where the parameters are passed from the caller to the callee. In some environments, the caller pushes each argument onto the stack, thus extending its stack frame, then invokes the callee. In other environments, the caller has a preallocated area at the top of its stack frame to concur the arguments information technology supplies to other subroutines it calls. This area is sometimes termed the outgoing arguments area or callout surface area. Under this approach, the size of the area is calculated past the compiler to be the largest needed by any chosen subroutine.
Use [edit]
Call site processing [edit]
Usually the telephone call stack manipulation needed at the site of a call to a subroutine is minimal (which is good since there can be many telephone call sites for each subroutine to be chosen). The values for the actual arguments are evaluated at the call site, since they are specific to the item call, and either pushed onto the stack or placed into registers, as determined past the used calling convention. The actual call educational activity, such every bit "branch and link", is then typically executed to transfer command to the code of the target subroutine.
Subroutine entry processing [edit]
In the called subroutine, the get-go code executed is usually termed the subroutine prologue, since it does the necessary housekeeping before the code for the statements of the routine is begun.
For instruction set up architectures in which the didactics used to call a subroutine puts the return accost into a register, rather than pushing it onto the stack, the prologue will commonly save the return accost past pushing the value onto the call stack, although if the chosen subroutine does non telephone call whatever other routines information technology may leave the value in the register. Similarly, the current stack pointer and/or frame pointer values may be pushed.
If frame pointers are being used, the prologue will typically prepare the new value of the frame pointer annals from the stack pointer. Space on the stack for local variables can then exist allocated by incrementally changing the stack pointer.
The Forth programming language allows explicit winding of the call stack (called in that location the "return stack").
Return processing [edit]
When a subroutine is fix to return, it executes an epilogue that undoes the steps of the prologue. This will typically restore saved register values (such as the frame pointer value) from the stack frame, pop the entire stack frame off the stack past changing the stack pointer value, and finally co-operative to the instruction at the return address. Under many calling conventions the items popped off the stack by the epilogue include the original argument values, in which case at that place usually are no further stack manipulations that demand to exist done by the caller. With some calling conventions, however, it is the caller's responsibility to remove the arguments from the stack after the return.
Unwinding [edit]
Returning from the called part will pop the top frame off the stack, perhaps leaving a return value. The more general act of popping 1 or more frames off the stack to resume execution elsewhere in the program is called stack unwinding and must be performed when non-local control structures are used, such every bit those used for exception handling. In this case, the stack frame of a function contains 1 or more entries specifying exception handlers. When an exception is thrown, the stack is unwound until a handler is found that is prepared to handle (catch) the type of the thrown exception.
Some languages have other control structures that require general unwinding. Pascal allows a global goto statement to transfer command out of a nested function and into a previously invoked outer function. This operation requires the stack to be unwound, removing as many stack frames as necessary to restore the proper context to transfer control to the target statement within the enclosing outer role. Similarly, C has the setjmp
and longjmp
functions that act as non-local gotos. Common Lisp allows command of what happens when the stack is unwound past using the unwind-protect
special operator.
When applying a continuation, the stack is (logically) unwound and then rewound with the stack of the continuation. This is not the only fashion to implement continuations; for example, using multiple, explicit stacks, application of a continuation can just activate its stack and wind a value to be passed. The Scheme programming language allows arbitrary thunks to be executed in specified points on "unwinding" or "rewinding" of the command stack when a continuation is invoked.
Inspection [edit]
The call stack tin sometimes be inspected as the plan is running. Depending on how the plan is written and compiled, the information on the stack tin exist used to determine intermediate values and function telephone call traces. This has been used to generate fine-grained automated tests,[iv] and in cases like Ruby and Smalltalk, to implement first-class continuations. As an example, the GNU Debugger (GDB) implements interactive inspection of the telephone call stack of a running, but paused, C programme.[5]
Taking regular-time samples of the call stack tin can exist useful in profiling the performance of programs, because if a subroutine's pointer appears on the phone call stack sampling data many times, it is probable a code bottleneck and should exist inspected for performance bug.
Security [edit]
In a language with gratuitous pointers or not-checked array writes (such as in C), the mixing of control flow data which affects the execution of code (the return addresses or the saved frame pointers) and simple program data (parameters or return values) in a telephone call stack is a security risk, possibly exploitable through stack buffer overflows every bit the most common type of buffer overflows.
I of such attacks involves filling one buffer with arbitrary executable code, and and then alluvion the same or some other buffer to overwrite some return address with a value that points direct to the executable lawmaking. As a result, when the role returns, the computer executes that code. This kind of an attack tin can be easily blocked with W^Ten.[ citation needed ] Similar attacks can succeed even with West^10 protection enabled, including the return-to-libc attack or the attacks coming from return-oriented programming. Various mitigations have been proposed, such as storing arrays in a completely separate location from the return stack, equally is the case in the Forth programming language.[6]
Run across also [edit]
- Automatic memory allotment
- Calling convention
- Coroutine
- Overhead (computing)
- Spaghetti stack
- Stack-based memory allocation
- Stack machine
- Stack trace
References [edit]
- ^ Krzyzanowski, Paul (February xvi, 2018). "Stack frames". Rutgers University. Archived from the original on 2021-08-28. Retrieved December nineteen, 2021.
- ^ "Understanding the Stack". cs.umd.edu. 2003-06-22. Archived from the original on 2013-02-25. Retrieved 2014-05-21 .
- ^ Alternative Microprocessor Design
- ^ McMaster, S.; Memon, A. (2006). Call Stack Coverage for GUI Test-Suite Reduction (PDF). 17th International Symposium on Software Reliability Applied science (ISSRE '06). pp. 33–44. CiteSeerXx.1.ane.88.873. doi:ten.1109/ISSRE.2006.19. ISBN0-7695-2684-5.
- ^ "Debugging with GDB: Examining the Stack". chemie.fu-berlin.de. 1997-10-17. Retrieved 2014-12-xvi .
- ^ Doug Hoyte. "The Along Programming Linguistic communication - Why YOU should larn it".
Further reading [edit]
- Dijkstra, Eastward. W. (1960). "Recursive Programming". Numerische Mathematik. 2 (one): 312–318. doi:10.1007/BF01386232.
- Wilson, P. R.; Johnstone, K. S.; Neely, Yard.; Boles, D. (1995). "Dynamic storage allocation: A survey and disquisitional review". Retention Management. Lecture Notes in Informatics. Vol. 986. pp. 1–116. CiteSeerX10.1.1.47.275. doi:x.1007/3-540-60368-9_19. ISBN978-3-540-60368-9.
- "ii.4. The Stack". MCS-4 Assembly Language Programming Transmission - The INTELLEC four Microcomputer System Programming Manual (PDF) (Preliminary ed.). Santa Clara, California, USA: Intel Corporation. Dec 1973. pp. 2-7–2-8. MCS-030-1273-1. Archived (PDF) from the original on 2020-03-01. Retrieved 2020-03-02 . (NB. Intel's 4-chip processor 4004 implements an internal stack rather than an in-memory stack.)
External links [edit]
- Office Calling and Frame Pointer Operations in 68000 Archived 2010-07-24 at the Wayback Machine
- The libunwind project - a platform-independent unwind API
colethavervist1955.blogspot.com
Source: https://en.wikipedia.org/wiki/Call_stack
0 Response to "C Variable Preserved on Stack After Running Program Again"
Post a Comment