Robert Bradshaw
Robert Bradshaw

Reputation: 11

Printf nasm trouble

I am in an assembly class, and I need to print out a white character "" a bunch of times for a project I am doing. I have been sitting here for hours trying to make the printW function work, so it would be called X times. The following code will print out 2 ""s, changing the initial cx to any number, does not change the number of "*"s the code prints. I am at my wits end. Can someone please find the issue with the code, and explain why it was an issue?

printBoard:
    mov ecx,0x00010
    cmp ecx,0
    loop printWhiteRow
    ret

printWhiteRow:
    call printW


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;print a string
printW:
    push ebp                ; set up stack frame
    mov ebp,esp
    mov eax, whiteChar              ; put a from store into register
    push eax                ; value of variable a
    call printf             ; Call C function
    add esp, 8              ; pop stack 3 push times 4 bytes
    mov esp, ebp            ; takedown stack frame
    pop ebp                 ; same as "leave" op
    ret                     ; return

Upvotes: 1

Views: 260

Answers (1)

Jester
Jester

Reputation: 58762

Some issues:

  1. You don't seem to know how loop instruction works.
  2. No idea what this is supposed to mean: add esp, 8 ; pop stack 3 push times 4 bytes. 3 times 4 is 12, and in any case you only pushed 1 argument.
  3. The cdecl calling convention defines ecx as caller-saved, so you need to save it if you want its value to be preserved.
  4. If you want to print a single character, why not use putchar?

Something like this should work better:

printBoard:
    mov ecx,0x00010
printWhiteRow:
    push ecx     ; save counter
    push ' '     ; char to print
    call putchar
    pop ecx      ; cleanup argument
    pop ecx      ; restore counter
    loop printWhiteRow
    ret

Same with printf:

printBoard:
    mov ecx,0x00010
printWhiteRow:
    push ecx       ; save counter
    push whiteChar ; string to print
    call printf
    pop ecx        ; cleanup argument
    pop ecx        ; restore counter
    loop printWhiteRow
    ret

Upvotes: 2

Related Questions