The Stack and Heap Flashcards
What happens to the stack when we do a function call? What happens when we return from this function?
A new stack frame is created for this new function. When we return from this function, the stack frame we created is no longer accessible.
What does a stack frame contain?
The arguments of the procedure, a place to hold local variables, information to be able to return from the call.
What are the three main registers used to implement the stack?
1) Instruction Pointer, which references the next instruction to execute. 2) The stack pointer, which references the top of the stack. 3) The stack base pointer, which is a reference to the current stack frame.
When we have made a function call to foo, we will have a pointer to the previous stack frame base pointer (EBP). What will we find if we look at the stack addresses: ESB -1, ESB -2, ESB -3.
ESB -1 is a pointer to the next instruction which will be executed after the function, ESB -2 is a pointer to where the results of the function will be stored, ESB -1 is a pointer to the arguments of the function.
Why might you not see some of the arguments on the stack in X_86?
Because in X_86, the first 6 arguments are placed in dedicated registers rather than the stack.
Why shouldn’t you return pointers to local variables in functions?
These are written on the stack, so may be overwritten. The same goes for returning data structures.
How would you use malloc to create space for an array of 5 integers?
int *h = (int *) malloc (5 * sizeof(int));
What do calloc and realloc do?
calloc works like malloc, but initialises all values to 0. realloc can be used to change the size of a structure pointed to by ptr.