title: Print array on asm... Why printf spoils the register?
body: <p>i want to print dynamic array with printf... But after call printf i have some strange behavior(for me). Call printf changes unrelated register.</p>
  <p>My questions:</p>
  <ol>
  <li>In print_array gdb show that after printf register %rcx was changed... Why is this happening and and how to fix it?</li>
  <li>If we comment out print_array the program crashes in call free... I really don't understand why? Help please</li>
  </ol>
  <p>All program:</p>
  <pre><code>    .text
      .global main
  
      print_array:
      pushq   %rbp
      movq    %rsp, %rbp
      
      xor %rax, %rax
      mov %rdi, %rbx
      mov %rsi, %rax
      dec %rax
      imul $4, %rax
      add %rax, %rdi
      mov %rdi, %rcx
  
      print_loop:
      cmp %rbx, %rcx
      jl stop
  
      xor %rdi, %rdi
      xor %rsi, %rsi
      lea one_element(%rip), %rdi
      mov (%rbx), %rsi
      xor %rax, %rax
      call printf
  
      add $4, %rbx
      jmp print_loop
      stop:
      popq    %rbp
      retq
  
      main:
      pushq   %rbp
      movq    %rsp, %rbp
      movl    $24, %edi
      callq   malloc
      movq    %rax, -8(%rbp)
      cmpq    $0, -8(%rbp)
      je broken
      movl    $1, (%rax)
      movl    $2, 4(%rax)
      movl    $3, 8(%rax)
      movl    $4, 12(%rax)
      movl    $5, 16(%rax)
      movl    $6, 20(%rax)
      mov %rax, %r10
  
      mov %rax, %rdi
      mov $6, %rsi
      call print_array
  
      xor %rdi, %rdi
      xor %rsi, %rsi
      xor %rcx, %rcx
      lea elements(%rip), %rdi
      mov (%r10), %rsi
      mov 4(%r10), %rdx
      mov 8(%r10), %rcx
      mov 12(%r10), %r8
      mov 16(%r10), %r9
      xor %rax, %rax
      call printf
  
      mov %r10, %rdi
      callq free
      xor %rax, %rax
      popq    %rbp
      retq
      broken:
          xor %rax, %rax
          popq    %rbp
          retq
  
      data:
      elements: .string &quot;First element: %d second: %d third: %d fourth: %d fifth: %d\n&quot;
      one_element: .string &quot;Element: %d\n&quot;
  </code></pre>