gpt4 book ai didi

c - 将 char 作为参数传递给函数,将其存储在堆栈上的非默认位置

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:04 25 4
gpt4 key购买 nike

void myFunc(char dummy) {
char *addrFirstArg = &dummy;
}

int main() {
char dummy = 42;
myFunc(dummy);
return 0;
}

我在 gdb 下运行上面的代码并在 myFunc 处添加一个断点。我一步计算 addrFirstArg 值并检查它。

我也是

info frame
to spit out information about the frame myFunc. As far as my understanding of the C stack implementation goes, I expect that addrFirstArg should be 8 bytes above the base pointer for the frame myFunc.

This is the output that I see:

(gdb) p &dummy
$1 = 0xffffd094 "*\202\f\b\032\004"

(gdb) info frame
Stack level 0, frame at 0xffffd0b0:
eip = 0x8048330 in findStackBottom (reporter.c:64); saved eip 0x8048478
called by frame at 0xffffd170
source language c.
Arglist at 0xffffd0a8, args: dummy=42 '*'
Locals at 0xffffd0a8, Previous frame's sp is 0xffffd0b0
Saved registers:
ebp at 0xffffd0a8, eip at 0xffffd0ac

(gdb) x/1c 0xffffd0b0
0xffffd0b0: 42 'a'

因此,在 myFunc 框架内,ebp 指向位置 0xffffd0a8,而 dummy 的地址是 0xffffd094,它在 ebp 下面 0x14 字节,而不是在它上面 0x8 字节。

如果我声明我的虚拟对象是一个 int 并且 myFunc 接受一个 int 参数,这种“差异”就会消失。

我对这种行为很感兴趣。它是可重现的 - 我运行了很多次。

最佳答案

如果使用 gcc -S,您会更好地看到差异;在 char 的情况下我们有

char case                       int case (diffs)

pushl %ebp
movl %esp, %ebp
subl $20, %esp subl $16, %esp
movl 8(%ebp), %eax x
movb %al, -20(%ebp) x
leal -20(%ebp), %eax leal 8(%ebp), %eax
movl %eax, -4(%ebp)
leave
ret

当函数进入时,栈是(top on top):

esp     return address
esp+4 2A 00 00 00

这是因为单个字符以这种方式“压入”堆栈

movsbl  -1(%ebp), %eax
movl %eax, (%esp)

x86 是小端。

“序言”之后的情况是这样的

esp            (room for local char dummy - byte 42) ...
...
ebp-4 room for char *
esp+20 = ebp ebp
ebp+4 return addr
ebp+8 2A 00 00 00

然后将“char”(存储为 32 位整数)从 ebp+8(原始值由 main“推送”,但为“32 位”)取出到 eax,然后将较低的低位字节放入在本地存储中。

int 的情况更简单,因为我们不需要对齐,我们可以“直接”获取堆栈上任何内容的地址。

esp             ...
...
ebp-4 room for int *
esp+16 = ebp ebp
ebp+4 return addr
ebp+8 2A 00 00 00

因此,在第一种情况下(char 情况),esp 被递减 4 个字节以保存单个 char:有一个额外的本地存储。

为什么会这样?

如您所见,单个字符作为 32 位“整数”(eax) 被压入堆栈,并以相同的方式在 eax 中取回。此操作没有字节序问题。

但是,如果它返回 char 的 ebp+8 地址并且机器不是小端字节序怎么办?在这种情况下,ebp+8 指向 00 00 00 2A并引用 *dummy会给出 0,而不是 42。

因此,一旦将“伪整数”(无论字节序是什么,CPU 都会连贯地处理的操作)放入寄存器中,LSByte 必须放入本地存储中,以便保证其地址指向该字符(低字节)当被引用时。这就是额外代码的原因以及未使用 ebp+8 的事实:endianness 以及地址对齐的要求(例如,在大端情况下 00 00 00 2A 中的 2A会有一个奇怪的地址。

关于c - 将 char 作为参数传递给函数,将其存储在堆栈上的非默认位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10764532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com