Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3920720
  • 博文数量: 534
  • 博客积分: 10470
  • 博客等级: 上将
  • 技术积分: 4800
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-26 14:08
文章分类

全部博文(534)

文章存档

2024年(1)

2021年(1)

2019年(1)

2017年(1)

2016年(2)

2013年(2)

2012年(10)

2011年(43)

2010年(10)

2009年(17)

2008年(121)

2007年(252)

2006年(73)

分类: C/C++

2008-03-28 09:16:18

昨天写东西发现个小问题, 编译没有任何问题, 但就是出错了. 下面是简单的代码:

#include <stdio.h>
#include <stdarg.h>

static char msg[1024];

static int my_print1(FILE *fp, const char *fmt, ...)
{
  return (fprintf(fp, fmt));
}

static int my_print2(FILE *fp, const char *fmt, ...)
{
  int t;
  va_list body;

  va_start(body, fmt);
  t = vsnprintf(msg, 1024, fmt, body);
  va_end(body);

  return (fprintf(fp, msg));
}

int main(int argc, char **argv)
{
  my_print1(stderr, "%s int.%d \n", "char print", 3);
  my_print2(stderr, "%s int.%d \n", "char print", 3);
 
  return (0);
}


再看看用gcc编译后的汇编代码:

    .file    "a.c"
    .text
    .type    my_print1,@function
my_print1:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $8, %esp
        
    subl    $8, %esp
    pushl    12(%ebp)
    pushl    8(%ebp)
    call    fprintf
    addl    $16, %esp
    leave
    ret
.Lfe1:
    .size    my_print1,.Lfe1-my_print1
    .type    my_print2,@function
my_print2:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $8, %esp
        
    leal    16(%ebp), %eax
    movl    %eax, -8(%ebp)
    pushl    -8(%ebp)
    pushl    12(%ebp)
    pushl    $1024
    pushl    $msg
    call    vsnprintf
    addl    $16, %esp
    movl    %eax, -4(%ebp)
        
    subl    $8, %esp
    pushl    $msg
    pushl    8(%ebp)
    call    fprintf
    addl    $16, %esp
    leave
    ret
.Lfe2:
    .size    my_print2,.Lfe2-my_print2
    .section    .rodata
.LC0:
    .string    "char print"
.LC1:
    .string    "%s int.%d \n"
    .text
.globl main
    .type    main,@function
main:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $8, %esp
    andl    $-16, %esp
    movl    $0, %eax
    subl    %eax, %esp
    pushl    $3
    pushl    $.LC0
    pushl    $.LC1
    pushl    stderr
    call    my_print1
    addl    $16, %esp
    pushl    $3
    pushl    $.LC0
    pushl    $.LC1
    pushl    stderr
    call    my_print2
    addl    $16, %esp
    movl    $0, %eax
    leave
    ret
.Lfe3:
    .size    main,.Lfe3-main
    .local    msg
    .comm    msg,1024,32
    .ident    "GCC: (GNU) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)"


看看输出结果:
[gan@gan stack]$ ls
a.c  a.out  a.s

[gan@gan stack]$ a.out
媫鼖]魦u鴫靅脨怳夊WVS?"???伱y? int.134513410
char print int.3

一个为乱码, 另外一个才是我们想要的结果.
阅读(3082) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~