You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 string pfmt uses %s, which expects a pointer to a null-terminated string. But you're passing lea rsi,[n] — n holds the return value of scanf (1 for a successful single-string read), not the input string itself. This makes printf try 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 defined n as 100 bytes of zeros, but scanf returns 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

  1. Fixed n's definition: Swapped the 100-byte array for an 8-byte doubleword (dq) to properly store scanf's 64-bit return value.
  2. Corrected printf's argument: Now we pass the address of s (your input string) instead of n, which aligns with the %s format specifier's requirement for a string pointer.
  3. Optional Error Checking (Bonus): If you want to handle cases where scanf fails (like EOF), you can add this right after storing rax in n:
    cmp rax, 1
    jne exit ; Jump to exit if scanf didn't successfully read a string
    

内容的提问来源于stack exchange,提问作者Swapnil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:12:29