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

在NASM中调用C语言printf函数出现换行次数递增问题求助

问题分析与解决方案

问题根源

你的代码违反了x86-64 System V调用约定:调用可变参数函数(如printf)时,必须将AL寄存器设置为通过XMM寄存器传递的参数数量。

printStr函数未设置AL的值,导致printf错误地从栈中读取额外数据,引发栈错位。随着调用次数增加,栈错位会破坏.data段中string_format的内存内容,使得换行符数量逐次递增。

修正代码

修改printStr函数

添加mov al, 0(未使用XMM寄存器,故设置为0):

SECTION .data
    endLine db 0Ah, 0
    integer_printf:     db  '%d',   10,0
    float_printf        db  '%f',   10,0
    string_format       db  '%s',   10,0

SECTION .text
    extern printf

printStr:
    mov rdi, string_format
    mov al, 0          ; 告知printf未使用XMM寄存器
    call printf
    ret

同步修正其他打印函数

确保printInt和printFloat也遵守调用约定:

  • printInt:使用%d无需XMM寄存器,设置al=0
printInt:
    mov rdi, integer_printf
    mov al, 0
    call printf
    ret
  • printFloat:使用%f通过xmm0传递参数,设置al=1
printFloat:
    mov rdi, float_printf
    mov al, 1          ; 告知printf使用了1个XMM寄存器
    call printf
    ret

原理说明

x86-64 System V调用约定中,可变参数函数通过AL的值确定XMM寄存器传递的参数数量。若AL值不正确,函数会尝试读取栈中不存在的参数,导致栈指针偏移,进而破坏内存中的其他数据(如你的string_format),最终出现换行次数递增的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:32:42