1

I would like to call the printf function from C with two integers. My format string is:

LC0:
    db "odd bits: %d, even bits: %d", 10, 0

I have the integer ob and eb:

ob: DD 0
eb: DD 0

and then I do at the end:

push dword [ob]
push dword [eb]
push LC0
call printf
add esp,8

However, this gives me the result Odd bits: [ob], Even bits: [ob, repeated] then gives me a segmentation fault. Am I calling the printf function wrong?

EDIT: I added LC1 as db "even bits: %d", 10 0, then redid:

push dword [ob]
push LC0
call printf
push dword [eb]
push LC1
call printf
add esp, 8

This gives me a REVERSED result, giving the eb to the LC0 string, and ob to the LC1 string, and, it gives a segmentation fault at the end. Any clue?

TheNotMe
  • 1,048
  • 2
  • 17
  • 33
  • This is not the problem, but you should push `eb` first, then `ob`, since you want to push the parameters from right to left. – Shahbaz Mar 26 '14 at 10:32
  • I fixed the reversed result, it is the original code, but I merely forgot to relink (sorry...) The seg fault still exists, though. – TheNotMe Mar 26 '14 at 10:38

1 Answers1

2

You're not adjusting the stack pointer correctly.

In your original code you were pushing 12 bytes, but only "popping" 8.

In your updated code you're pushing 8 bytes twice, i.e. 16 bytes in total, but only "popping" 8 bytes once.


As for the order in which the values are printed; in your original code you had:

push dword [ob]  
push dword [eb]
push LC0

You've declared LC0 as db "odd bits: %d, even bits: %d", 10, 0, so clearly you intended ob to the printed first. Arguments are push right-to-left, so you should push eb before ob.

Michael
  • 57,169
  • 9
  • 80
  • 125
  • Please see edit on the new result. This comes out because I am a newbie in the c-assmelby interaction. How do I correct this? – TheNotMe Mar 26 '14 at 10:33
  • Your edit is what I refer to as "your updated code". I'm talking about the segfault here, not the order of the values you get. – Michael Mar 26 '14 at 10:35
  • Works! Did not realize that the `add esp, 8` is actually `popping` so that assembly can go on and finish itself. I re-put only 1 format string, and pushed in reverse, and popped 12 (eb, ob and lc0). Much appreciated! – TheNotMe Mar 26 '14 at 10:43