Skip to content
Advertisement

x86 NASM | Input in Loop working only the first and third time

I have a loop that runs succesfully 3 times, but the input I have in this loop works only the first time. I am new to assembly so pls have patience.

Code:

JavaScript

Output:

JavaScript

Well, later I thought that the loop might not running a third time, so I changed the code a bit.

New Code:

JavaScript

New Output:

JavaScript

Explaination:

0 is the counter and 2 my input. 1 and 2 are the counter and the second 2 is my second input, which means that the loop runs succesfully, it just ignores the code for input the second time it runs

Also, do the straight lines I have in my code to visualize the scopes make my code any more readable?

Advertisement

Answer

Peter already did a great job of covering most of this in the comments, but I thought I’d go into more detail:

The x86 loop instruction assumes you have a counter in ecx. loop automatically decrements ecx and jumps to the loop label if ecx is not 0. Since you’re calling linux syscalls in a loop, and linux expects the buffer pointer to be in ecx, you should probably use a different register as your loop counter and some sort of jump instruction to do this instead:

JavaScript

However, calling syscalls in a loop is not very efficient. Instead, you could do something like this:

JavaScript

This calls read once, but still calls write in a loop to write the counter and values of d.

To skip the trailing newline in your input, you could try doing this after your call to read (remember eax has the number of bytes read):

JavaScript

The newline will still be stored in memory, but you won’t print it, because you’ll loop one fewer times.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement