C 语言中指针作为函数参数的一个问题?
在下面的代码中:
#include <stdio.h>
int *foo(int *pp)
{
int ppp = 2333;
pp = &ppp;
return pp;
}
int main(void)
{
int *p = NULL;
int num = 520;
p = #
foo(p);
return 0;
}
编译成汇编代码是这样的:
foo:
.LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
subl $16, %esp
movl $2333, -8(%ebp)
leal -8(%ebp), %eax
movl %eax, -4(%ebp)
movl -4(%ebp), %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size foo, .-foo
.globl main
.type main, @function
main:
.LFB1:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
subl $20, %esp
movl $0, -4(%ebp)
movl $520, -8(%ebp)
leal -8(%ebp), %eax
movl %eax, -4(%ebp)
movl -4(%ebp), %eax
movl %eax, (%esp)
call foo
movl $0, %eax
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
在这里,
pp
的访问都是通过
-4(%ebp)
来进行的,但是,
pp
作为一个参数,不是应该是在
+8(%ebp)
吗?
然后是另外一段代码:
#include <stdio.h>
void foo(int *pp)
{
int *ppp;
ppp = pp;
}
int main(void)
{
int *p = NULL;
int num = 520;
p = #
foo(p);
}
编译成汇编代码是这样的:
.file "jjda2.c"
.text
.globl foo
.type foo, @function
foo:
.LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
subl $16, %esp
movl 8(%ebp), %eax
movl %eax, -4(%ebp)
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size foo, .-foo
.globl main
.type main, @function
main:
.LFB1:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
subl $20, %esp
movl $0, -4(%ebp)
movl $520, -8(%ebp)
leal -8(%ebp), %eax
movl %eax, -4(%ebp)
movl -4(%ebp), %eax
movl %eax, (%esp)
call foo
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE1:
.size main, .-main
.ident "GCC: (Ubuntu 4.8.2-19ubuntu1) 4.8.2"
.section .note.GNU-stack,"",@progbits
然后这里面对
pp
的访问就是
+8(%ebp)
了。
为什么同样是一个参数,访问会有如此大的不同呢?
谢谢大家!
色部工口子
9 years, 7 months ago