【问题标题】:Segmentation fault when calling printf from a function - 64 bit [duplicate]从函数调用 printf 时出现分段错误 - 64 位 [重复]
【发布时间】:2018-04-18 12:21:13
【问题描述】:

当我从函数调用 printf 函数时出现分段错误,但从主函数调用时它工作得非常好:

代码:

extern  printf

SECTION .data
    msg:    db "Hello", 0 ; Zero is Null terminator 
    fmt:    db "%lf", 10, 0 ; printf format string follow by a newline(10) and a null terminator(0), "\n",'0'
    d1: dq 13.0
    d2: dq 15.0
    result : dq 0

SECTION .text
    global main

main:

    push rbp ; Push stack

      ; mov  rdi,fmt ; set the format for print
      ; mov rsi,msg ; set first parameter
      ; mov rax,1 ; one floating point
      ; movq xmm0, [d1]
      ; call printf

    call get_input 

    pop rbp     ; Pop stack
    mov rax,0   ; Exit code 0
    ret         ; Return


    get_input:
       mov  rdi,fmt ; set the format for print
       mov rsi,msg ; set first parameter
       mov rax,1 ; one floating point
       movq xmm0, [d1]
       call printf        
    ret

制作文件:

nasm -g -f elf64 -F dwarf printf.s -o printf.o
gcc -g -Wall -o printf printf.o

【问题讨论】:

  • 看不到C,所以修复了标签。
  • 我相信 printf 是一个外部 C 函数,所以我使用 gcc 链接器来使其工作。
  • 是的,printf 是 C 和 C++ 标准库的一部分。它也可能在您的平台上使用 C 代码的标准调用约定,甚至可能是用 C 编码的。不过,C 与您的问题无关,因为您不使用 C。

标签: linux assembly printf x86-64 libc


【解决方案1】:

调用 printf 之前堆栈需要 16 字节对齐。

在调用get_input之前是对齐的,返回地址使其错位,所以get_input需要减8再对齐。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2011-01-08
    相关资源
    最近更新 更多