jphollowed jphollowed - 1 year ago 94
C Question

Finding missing C code, given assembly code?

The code is

int f(int x, int y, int z) {
if (/* missing code here */)
return z;
return -z;

And the assembly is

pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %eax
cmpl 12(%ebp), %eax
jge .L2
movl 16(%ebp), %eax
jmp .L3
movl 16(%ebp), %eax
negl %eax
popl %ebp

And the question asks for me to find what the missing test expression must be to yield the assembly code given. Okay, easy enough. There is an obvious comparison going on between
. The
operator is going to preform the jump into the body of the loop if
12(%ebp) > %eax

The possible choices are





My answer was
, since
is a reference to
, and it is the destination. But this answer was wrong, and I do not see how. Any hints? Thank you so much.

Answer Source

Here is the annotated x86 assembly:

pushl %ebp ; save the old stack movl %esp, %ebp ; set up your local, new stack movl 8(%ebp), %eax ; take the first function argument and store it into eax cmpl 12(%ebp), %eax ; compare the 2nd function arg with the 1st (in eax)

After this, there's a jge which means, essentially, "jump if greater than or equal", which you can do after the cmp instruction.

This means that it jumps if the first argument is greater than the second argument, and thus, x >= y.

However, this jump (to L2) will actually negate z, and then return z. What you actually want is the jump to L3, which would happen if x < y, which should be the end result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download