HW1 released: 01/26, 22:00 due: 02/02, 23:59 Answer the following questions. Submit your answers to Canvas assignments. There is an entry for this homework. 1. C pointer basics. Below is a piece of valid C code. Read it and answer questions: #include void foo(int p) { p = p + 1; } void bar(int *p) { int w = *p; w = w + 1; } void baz(int *p) { *p = *p + 1; } int main() { int x=0; foo(x); printf("foo: %d\n", x); bar(&x); printf("bar: %d\n", x); baz(&x); printf("baz: %d\n", x); } 1.a What the output of this program? (you can copy-paste the code to a file, compile it, and then run) [answer: foo: 0 bar: 0 baz: 1 ] 1.b What does "&" in "bar(&x)" mean? Explain in one sentence. [answer: "&" means to get the memory address of the variable "x" (which is on stack btw). ] 1.c What does "*" in "int w = *p;" mean? Explain in one sentence. [answer: "*" means to dereference the pointer "p"; in other words, to get the value from the memory pointed by "p". ] 2. Stack frame. Study handout.week2a (https://naizhengtan.github.io/22spring/notes/handout_w02a.pdf) Answer the questions below. Consider the state of the stack when arriving at line 21 (which is empty) of as.txt (the right panel). Below is the stack. Notes: -- each slot is 8bytes (indicated by "[8B]") -- %rbp and %rsp point to the beginning of the slot. -- (if you find the above bullet useless/confusing, you can ignore it.) high | ... [8B] | | previous %rbp | <- %rbp (base pointer) | x (in main) [=?] | | arg [=?] | <- %rsp | [=??] | | | low 2.a What are the values of "x" and "arg" (indicated by "[=?]")? [answer: x=0, arg=8] 2.b If the program continue to run, what will appear in the next slot of the stack (indicated by "[=??]" in the stack above)? [hint: your answer should be the address of one line of code. Why? Revisit the assembly instruction "call".] [answer: address of line 24 in the assembly code (as.txt).] 2.c Now consider what happens when the call and the function prologue is executed (line 42 in as.txt). [update 1/29: the stack below is when %rip points to line 42; meaning line 42 hasn't been executed.] high | ... | A | previous %rbp | B | x (in main) | C | arg | D | [=??] | E | address A ("pr") | <- %rbp F | x (in f) | [%rbp-8] | | [%rbp-16] | address ?? | [%rbp-24] | | <- %rsp low "pr" = "previous rbp" (which was actually address A) What does the stack element "%rbp-24" contain (indicated by "address ??")? Again, it contains a pointer, pointing to somewhere on stack. Choose from address A--F (labels on the left of the stack). Explain why in 1-2 sentences. [answer: C "ptr" is a local variable defined in function "main" which is passed to "f" through the first argument (%rdi). Later, the value of the argument (%rdi) is copied to the current position in line 33 of as.txt. See also line 23 in the C code (example.c).]