调用c函数时的分段错误

时间:2013-11-19 06:17:14

标签: c gcc assembly cygwin

我是x86-64程序集中的新手,我正在运行一个简单的x64汇编代码:

.global main

.text
main:                                
    mov     $message, %rdi       
    sub     $8, %rsp             
    call    puts                 
    add     $8, %rsp             
    ret                          
message:
    .asciz "Hello, World"        

在cygwin下使用gcc编译代码后,它总是返回错误:

segmentation error

但如果我删除

call puts

程序运行没有错误。那么这个调用声明有什么问题?

1 个答案:

答案 0 :(得分:0)

您必须在 只读数据 部分定义message ...
像这样......

.rodata                               # read-only data section
message:
    .string    "Hello, World!"

在32位机器上,使用AT& T语法,代码如下......

.section .rodata
msg:
    .string    "Hello, World!"        # msg is in the read only data section.

.section .text
    .globl    main
    .type     main, @function
main:
    pushl    %ebp
    movl     %esp, %ebp
    andl     $-16, %esp
    subl     $16,  %esp

    movl     $msg, (%esp)             # We move the argument of puts to (%esp)
    call     puts                     # puts is called

    movl     $0,   (%esp)             # moved the argument of(0) exit to (%esp)
    call     exit                     # exit is called