【问题标题】:What's the difference between puts and printf in C compiled into Assembly languageC编译成汇编语言的puts和printf有什么区别
【发布时间】:2016-04-30 22:05:20
【问题描述】:

这是我使用puts()的C程序:

#include <stdio.h>
int main(void){
puts("testing");
}

使用gcc -S -o sample.s sample.c编译成Assembly后,我得到了:

        .file   "sample.c"
        .section        .rodata
.LC0:
        .string "testing"
        .text
.globl main
        .type   main, @function
main:
        pushl   %ebp
        movl    %esp, %ebp
        andl    $-16, %esp
        subl    $16, %esp
        movl    $.LC0, (%esp)
        call    puts
        leave
        ret
        .size   main, .-main
        .ident  "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)"
        .section        .note.GNU-stack,"",@progbits

我也是这样做的,这次我使用 printf() 而不是 puts,这就是我得到的:

    .file   "sample.c"
        .section        .rodata
.LC0:
        .string "testing"
        .text
.globl main
        .type   main, @function
main:
        pushl   %ebp
        movl    %esp, %ebp
        andl    $-16, %esp
        subl    $16, %esp
        movl    $.LC0, %eax        //this is the difference
        movl    %eax, (%esp)
        call    printf
        leave
        ret
        .size   main, .-main
        .ident  "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)"
        .section        .note.GNU-stack,"",@progbits

这是我不明白的,printf() 函数mov $.LC0 到%eax,然后mov %eax 到(%esp) 而puts() 函数mov %.LC0 直接到(%esp)。 我不知道这是为什么。

【问题讨论】:

  • 这可能是因为printf 是一个可变参数函数,它们的调用方式与具有固定参数数量的函数不同。
  • 有趣的是,在 os x 上使用 clang,两个程序都编译成同一个程序集。
  • 还有为什么GCC在linux上编译位置依赖代码?
  • 编译时开启优化。如果没有优化,GCC 会生成糟糕的代码,这些代码会做很多不必要的事情。
  • 汇编输出在低于最大优化级别时无关紧要,您会看到编译器使代码比需要的更冗长,以便在调试器或人工阅读中更容易理解

标签: c gcc assembly


【解决方案1】:

在汇编级别,这两个函数之间的最大区别在于 puts() 函数将只接受一个参数(指向要显示的字符串的指针),而 printf() 函数将接受一个参数(一个指针到格式字符串),然后是堆栈中任意数量的参数(printf() 是一个可变参数函数)。

请注意,绝对不会检查参数的数量,它仅取决于在格式字符串中遇到字符 % 的次数。例如,这种特殊性用于格式字符串格式漏洞利用方法,以交互方式探索进程堆栈的内容。

所以,基本上,区别在于puts() 只有一个参数,而printf() 是可变参数函数。

如果您想更好地理解这种差异,请尝试编译:

#include <stdio.h>

int main(void) {
    printf("testing %d", 10);
}

【讨论】:

猜你喜欢
  • 2011-01-28
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多