0

Trying to write msg1 and msg2 sequentially on stdout to get something like this:

Hello
World

But instead prints this :

Hello
World
World

section .data     
                              
msg1    db 'Hello',10,0
msg2    db 'World',10,0

len1    equ     $- msg1                
len2    equ     $- msg2

section .text
global CMAIN
CMAIN:
   mov ebp, esp; for correct debugging

   mov edx,len1        
   mov ecx,msg1         
   call printString     
   

   mov edx, len2
   mov ecx, msg2
   call printString 
   
   mov eax,1            
   int 0x80        
 
printString:
   mov ebx,1          
   mov eax,4           
   int 0x80       
   xor eax, eax
   ret
 

Please could somebody explain me why this happens?

1 Answers1

1
msg1    db 'Hello',10,0
msg2    db 'World',10,0

len1    equ     $- msg1                
len2    equ     $- msg2

The $ symbol always stands for the current address. So len1 equ $ - msg1 sets len1 to the number of bytes between the start of msg1, and the address reached on the line where len1 is defined - which is after the World string. Thus len1 is set to 14, and when you write len1 bytes on the first write, you are writing both Hello and World. Then you go on to write World again with the second write.

(You also include the null bytes, which don't show up on a terminal but will be undesirable if you redirect output to a file. Keep in mind that write doesn't pay any attention to null-termination; if there is a null byte included in the count of bytes to be written, it writes it.)

So what you want instead is

msg1    db 'Hello',10
len1    equ     $ - msg1    
msg2    db 'World',10
len2    equ     $ - msg2

Now len1 is defined immediately after the string whose length it's supposed to represent, so its value will be 6 as desired. I also removed the 0 bytes from both strings.

Nate Eldredge
  • 24,174
  • 2
  • 31
  • 43
  • 1
    We already have a canonical duplicate for this, [In NASM labels next to each other in memory are causing printing issues](https://stackoverflow.com/q/26897633). (Which has links to [How does $ work in NASM, exactly?](https://stackoverflow.com/q/47494744) for full details). – Peter Cordes Sep 08 '20 at 22:37
  • @PeterCordes: Ah, thanks. Interesting, it's precisely the same bug on a different OS, even including the unwanted null bytes. I guess there is nothing new under the sun. – Nate Eldredge Sep 08 '20 at 22:41