I use nasm. Say I want to have a loop and each loop add something to a buffer, here is the buffer:

buf: times 0ffh db 0

Here is the loop the loop:

xor al, al
mov edi, buf
theloop:
  cmp al, 0ffh
  je done
  inc al ; add 1 to al
  stosb ; put al into edi
  jmp theloop
done:
  ret

Between stosb and jmp theloop do I need to increment edi or not?

Dani AI

Generated

Short answer: is right — you do not need to manually inc edi after stosb. The string-store instruction adjusts the destination pointer for you. was on the right track thinking about the buffer layout, though.

A few practical caveats that are often missed:

  • STOSB uses ES:(D)I as the destination and will add or subtract 1 from (D)I depending on the direction flag (DF). If DF might be set by prior code, explicitly clear it with cld before the loop to force forward increments.
  • The pointer register used depends on operand-size: DI (16-bit), EDI (32-bit) or RDI (64-bit). In 64-bit flat memory models, segment bases are effectively ignored and addresses are normally loaded with lea/RIP-relative addressing rather than plain mov immediates. Adjust your addressing for the assembly mode you build in.

Useful alternatives and tips:

  • If you want to fill with a single repeated byte, rep stosb with the count in CX/ECX/RCX is much simpler and faster. If each byte changes (as in your incrementing-AL example) keep the loop and let stosb move the pointer.
  • Beware of buffer size and off-by-one: make sure the times allocation matches the number of stores you actually perform. Also respect calling conventions: if this code runs inside a function, consider which registers need saving/restoring.

These points should clarify when manual inc edi is necessary (rare when using stosb) and how to make the loop robust across different modes and environments.

Recommended Answers

All 3 Replies

Yes, if your intention is to have 255 values spread out across the buffer.

Of course not. stosb increments EDI automatically.

commented: Good catch! +12

Good catch . I was thinking too primitively.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.