64位Linux平台下Yasm汇编中scanf与printf调用异常的修正请求
Fixing Your 64-bit Yasm Input/Output Code
Let's break down what's going wrong here and fix your code step by step:
Key Issues in Your Original Code
- Mismatched argument for
printf: Your format stringpfmtuses%s, which expects a pointer to a null-terminated string. But you're passinglea rsi,[n]—nholds the return value ofscanf(1 for a successful single-string read), not the input string itself. This makesprintftry to interpret the integer 1 as a memory address for a string, which is invalid and causes the missing output. - Overly large storage for
n: You definednas 100 bytes of zeros, butscanfreturns a 64-bit integer (the count of successfully read items). Storing this in an 8-byte value is more efficient and correct.
Corrected Code
segment .data n dq 0 ; Store scanf's return value (64-bit integer, only needs 8 bytes) s times 100 db 0 ; char s[100] to hold input string fmt db "%s",0 pfmt db "The input was %s",0x0a,0 extern printf extern scanf segment .text global main main: ; Read input string into s lea rdi, [fmt] lea rsi, [s] xor eax, eax call scanf ; Save scanf's return value (optional, useful for error checking) mov [n], rax ; Print the input string lea rdi, [pfmt] lea rsi, [s] ; Pass pointer to the input string, not n xor eax, eax call printf ret
What Changed
- Fixed
n's definition: Swapped the 100-byte array for an 8-byte doubleword (dq) to properly storescanf's 64-bit return value. - Corrected
printf's argument: Now we pass the address ofs(your input string) instead ofn, which aligns with the%sformat specifier's requirement for a string pointer. - Optional Error Checking (Bonus): If you want to handle cases where
scanffails (like EOF), you can add this right after storingraxinn:cmp rax, 1 jne exit ; Jump to exit if scanf didn't successfully read a string
内容的提问来源于stack exchange,提问作者Swapnil
相关产品推荐
相关产品推荐

