Tutorial :What are the exact contents of a program stack in C?



Question:

I want to know the exact contents of a program stack.

How is the branching operation done?

What is meant by memory dump while debugging a program using gdb?

Does it give the program stack?

TIA, Praveen


Solution:1

The C language itself doesn't mandate the use of a stack at all - it defines behaviour rather than implementation.

However, in the common case, the program stack is used to store several things:

  • Objects declared with auto storage duration (ie. ordinary, non-static local variables);
  • Function parameters;
  • The return address (the location in the code where execution should resume after a return; or the end of the current function is reached);
  • Memory allocated with the non-standard alloca() function;
  • Temporary values required by the compiler, such as the saved contents of registers, housekeeping information for alloca(), the size of variable-length arrays and intermediate values used in calculations.

This is not an exhaustive list - other, more exotic things like Trampolines are also sometimes stored on the stack. In general, it is a temporary storage area for working items that will not be needed after the current function returns to its caller.

A "backtrace" in a debugger shows some (but not all) of the contents of the stack.


Solution:2

The stack is a memory area which contains subroutine arguments, local variables and return addresses from subroutines.

On many architectures, Intel's included, the stack grows from the top down - meaning that the stack pointer is decremented every time data is pushed to the stack.

A typical function call sequence will look like this:

  • Push the arguments
  • Jump to the subroutine (which pushes the return address to the stack)
  • In some languages, (Pascal, for example) the base pointer is pushed to the stack.
  • The called subroutine allocates space on the stack for its local variables.

To produce a stack trace, the runtime environment simply scans the stack to determine where the return addresses point to. I wrote "simply," but it's not that simple if the base pointers weren't saved to the stack, because it might be impossible to determine where any stack frames other than the current one are located.


Solution:3

see the link below which can give you a better idea Variables and Memory

it gives stack trace before the memory corruption happens.that stack trace is the series of function calls that were made along with the arguments passed.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »