c - 调用c函数时出现段错误

标签 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

程序运行没有错误。那么这个call out语句有什么问题呢?

最佳答案

您必须在只读数据部分定义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

关于c - 调用c函数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20064530/

相关文章:

c - 在 C 中,将结构作为参数传递给 printf 的预期行为是什么?

c++ - 返回值两份

C90 printf with\n or\r\n 在 cygwin 中不工作;但是 fflush(标准输出);工作正常。为什么?

c - 在 C 中追加数字

c - 在生产代码库 cppUnit 中模拟一个 c 文件

c - 如何在 ubuntu 11.04 下编译 libsndfile?

c - "Run configurations"中没有可配置的参数(Eclipse Luna)

assembly - 为什么IA-32具有非直观的主叫方和被叫方注册保存约定?

c++ - 我如何使用汇编程序从英特尔处理器中获取随机数?

assembly - 如何在DOS扩展器或DPMI环境下进行DMA传输?