Stack Exploration (ITS8020)
Mine navigeerimisribale
Mine otsikasti
In preparation for memory management, we shall investigate call stack contents.
Task
Write some small program for further exploration. The program should contain:
- function main() containing:
- at least 3 integers, with some (different) default values
- a string
- function void foo(int argument) containing:
- at least 2 integers, with some default values
This base program can do practically anything (including nothing), as long as the function foo() runs.
- Modify the program to print the memory addresses of all the variables. Use "%p" for printf() function. Use & operator on the variable to get the memory address as a value.
- Within function foo(), use the memory address of the first declared variable to print out the value of address which precedes it and the memory address which follows it. (Use * operator to read memory from given location)
- Can you go further? Can you read the variables of main() just by modifying the address of a variable in foo()? (Yes, but try it out)
- Can you print the string from main()? Is it located in the stack?
// note that there is a difference between the lines: char s[] = "foo:asdasdasd"; // is allocated on the stack char *s = "bar:dsadsadas"; // is not allocated on the stack
- Comment some of the lines which print the addresses of variables in main() (from task 1), check that your program does not use them -- can you still print them by using an address from foo()?
- Put the variables back to the stack. Write a function which tries to print out all the stack (4 bytes per line using printf() with "%08x\n". The program should crash at some point with a segmentation fault; this is the expected and desired result of the task and should be valued!
- Note: For your convenience print the memory location address, then its contents as decimal, hexadecimal, and char.