Check null character in assembly language

2019-07-07 19:48发布

问题:

I am new to assembly language. To be clear, this is homework. The problem is given a char *list, how can I find which character is the end of the string? So I have

xor ecx, ecx; //counter
loop1:
mov esi, list;
mov eax, [esi + ecx];
cmp eax, 0x00; //check if the character is null
je end;
inc ecx;
jmp loop1;

end:

however, the loop does not terminate when it reaches the end of the string. I wonder what I have done wrong. I have been finding solution in books and online, but they all look like what I did. Any help will be appreciated!

EDIT: yes, counter should be outside of the loop.

回答1:

  • You should not reset the counter as part of the loop.
  • You should not initialize the address as part of the loop.
  • The zero-termination is just a single byte but you test a complete dword.
  • The fewer jumps the better code you've written

Putting all of this together we get

  mov esi, list
  mov ecx, -1
loop1:
  inc ecx
  cmp byte [esi + ecx], 0x00; //check if the character is null
  jne loop1;


回答2:

You are reading several bytes at a time, and testing if they are all zero.

Try to read just one byte instead:

mov al, [esi + ecx];
cmp al, 0x00; //check if the character is null