{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

SampleMidtermCS3214S10

SampleMidtermCS3214S10 - CS 3214 Sample Midterm(Spring 2010...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 3214 Sample Midterm (Spring 2010) 1/9 Sample Midterm (Spring 2010) Solutions are shown in this style. This exam was given in Spring 2010. 1. Executing Programs on IA32 (30 pts) The following questions relate to how programs are compiled for IA32. a) (8 pts) Consider the following buggy program contained in a file sum.c #include <stdio.h> int sum(int a, int b) { int s = a + b; // return statement is missing } int main() { printf("%d\n", sum(1, 2)); } i. (4 pts) When the program is compiled with ‘gcc –o sum sum.c’ and run, it will output ‘3’. Explain why 3 is output! Since no optimization level is specified, the compiler will emit code for all statements it sees. This includes the computation of ‘s’ as the sum of ‘a’ and ‘b’. ‘s’ happens to be computed in register $eax, so it coincidentally becomes the return value of sum. ii. (4 pts) When the program is compiled with ‘gcc –O2 –o sum sum.c’ and run, it outputs a number such as -1074516556. Which analysis or optimization on the part of the compiler causes the generation of code that leads to this different result? The compiler determines that ‘s’ is not used and thus does not emit code to compute it - $eax in this case contains whichever value it had from the last time it was used. Or, if this function is inlined, the compiler may completely remove the function call since none of its computed values is used, then pass an uninitialized value to printf() (essentially, whatever is in memory at the address where printf expects its second argument). b) (12 pts) Consider the following assembly code, which was produced by gcc for a function ‘t’. The left column shows the result when compiling with
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
CS 3214 Sample Midterm (Spring 2010) 2/9 optimizations at level 1 (-O1). IA 32 Code,compiled with –O1 C Code t: pushl %ebp movl %esp, %ebp pushl %ebx subl $4, %esp movl 8(%ebp), %ebx movl (%ebx), %eax testl %eax, %eax je .L2 movl %eax, (%esp) call t .L2: movl %ebx, (%esp) call visit movl 4(%ebx), %eax testl %eax, %eax je .L6 movl %eax, (%esp) call t .L6: addl $4, %esp popl %ebx popl %ebp ret void t(struct node *node) { if (node->left) t(node->left); visit(node); if (node->right) t(node->right); } Provide a C version of function t()! Hint: t() accepts a pointer to this struct: struct node { struct node *left; struct node *right; } c) (5 pts) Consider the following program: #include <stdio.h> int mystery_function(int arg, ...) { int * p = &arg; int r = 1; while (*p) r = r * *p++;
Background image of page 2