drdot
drdot

Reputation: 3347

Is this movl instruction necessary?

I read the textbook "Computer Systems A programmer's perspective". It gives an example program:

/* read input line and write it back */
void echo(){
  char buf[8]; /* way too small !*/
  gets(buf);
  puts(buf);
}

The assembly code for this is:

1  echo:
2   pushl %ebp
3   movl  %esp, %ebp
4   pushl %ebx
5   subl  $20, %esp
6   leal  -12(%ebp), %ebx
7   movl  %ebx, (%esp)
8   call  gets
9   movl  %ebx, (%esp)        // This does not look useful for me
10  call  puts  
11  addl  $20, %esp
12  popl  %ebx
13  popl  %ebp
14  ret

Line 9 seems useless here since line 7 has already store buf at the top of the stack. Then it calls gets. When gets return, buf will be at the top of the stack.

My question is: Is line 9 useless here?

EDIT: This is Linux.

Upvotes: 2

Views: 70

Answers (2)

Pascal Cuoq
Pascal Cuoq

Reputation: 80295

My question is: Is line 9 useless here?

No. You cannot assume that gets will not change the value on the stack. It is its argument and it is allowed to modify it.

%ebx on the other hand is callee-save. The gets function has to preserve it.

Upvotes: 5

Pankaj Andhale
Pankaj Andhale

Reputation: 403

when you are calling the gets function, it may happen that it can modify the values of arguments(%ebx in your case). since you have not mentioned the other part of your code, can't say about that..but its good to store the buff into stack top again,after a function call..

Upvotes: 0

Related Questions