title: NASM Assembly while loop counter
body: <p>I'm writing a while loop in assembly to compile in the Linux terminal with nasm and gcc. The program compares x and y until y >= x and reports number of loops at the end. Here's the code:</p>
  
  <pre><code>segment .data
  
  out1    db "It took ", 10, 0
  out2    db "iterations to complete loop. That seems like a lot.", 10, 0
  x       db 10
  y       db 2
  count   db 0
  
  segment .bss
  
  segment .text
  
  global main
  extern printf
  
  main:
      mov    eax, x
      mov    ebx, y
      mov    ecx, count
      jmp    lp         ;jump to loop lp
  
  lp:
      cmp    ebx, eax   ;compare x and y
      jge    end        ;jump to end if y &gt;= x
      inc    eax        ;add 1 to x
      inc    ebx        ;add 2 to y
      inc    ebx
      inc    ecx        ;add 1 to count
      jp     lp         ;repeat loop
  
  end:
  
      push    out1      ;print message part 1
      call    printf
  
      push    count     ;print count
      call    printf
  
      push    out2      ;print message part 2
      call    printf
  
      ;mov    edx, out1               ;
      ;call   print_string            ;
                                      ;
      ;mov    edx, ecx                ;these were other attempts to print
      ;call   print_int               ;using an included file
                                      ;
      ;mov    edx, out2               ;
      ;call   print_string            ;
  </code></pre>
  
  <p>This is compiled and run in the terminal with:</p>
  
  <pre><code>nasm -f elf test.asm
  gcc -o test test.o
  ./test
  </code></pre>
  
  <p>Terminal output comes out as:</p>
  
  <pre><code>It took
  iterations to complete loop. That seems like a lot.
  Segmentation fault (core dumped)
  </code></pre>
  
  <p>I can't see anything wrong with the logic. I think it's syntactical but we've only just started learning assembly and I've tried all sorts of different syntax like brackets around variables and using <code>ret</code> at the end of a segment, but nothing seems to work. I've also searched for segmentation faults but I haven't found anything really helpful. Any help would be appreciated because I'm an absolute beginner.</p>