c - 压入堆栈位置的地址而不是该地址处的值

标签 c gcc assembly gnu-assembler att

我正在开发一个小型编译器项目,我似乎无法弄清楚如何推送堆栈位置的地址而不是该堆栈位置的值。我的目标是将保存整数值的堆栈位置地址作为 void 指针推送到打印它的 C 函数。我的最终目标是在函数中进行一些指针整数运算。我成功地从运行时库扩展调用 C 函数,但问题只是弄清楚如何在汇编中推送地址。

我的 C 函数。

void print(void* ptr){
    int* int_ptr = (int*)ptr;
    printf("*int_ptr is %d\n",*int_ptr);
}

我的 assembly

.globl main
main:
pushl %ebp
movl %esp, %ebp
subl $4, %esp

movl $42, %eax
movl %eax, -4(%ebp)

pushl -4(%ebp) 
//Instead of the value at -4(%ebp), I would like the address of -4(%ebp)
call print

addl $8, %esp
leave
ret

就我现在所拥有的而言,它会崩溃,因为我将值 42 转换为地址。有人可以指导我引用一些引用资料或资源以了解更多信息吗?

最佳答案

通常,您可以使用 LEA 获取基于堆栈的值的地址。指令获取-4(%ebp)的有效地址并将其放入寄存器中。然后您可以将该寄存器压入堆栈。 instruction set reference 中描述了LEA指令。这样:

Computes the effective address of the second operand (the source operand) and stores it in the first operand (destination operand). The source operand is a memory address (offset part) specified with one of the processors addressing modes; the destination operand is a general-purpose register.

在您的代码中,类似这样的内容会起作用:

lea -4(%ebp), %eax
push %eax

这应该有效地传递堆栈上-4(%ebp)的地址,以供函数print使用。

关于c - 压入堆栈位置的地址而不是该地址处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47732748/

相关文章:

c++ - 不同的行为取决于优化选项

c++ - 数组默认与列表初始化

c++ - limits.h 中的条件编译语句

一个时钟周期内的 C++ 字符串比较

c - 在 x86 Assembly 中组装代码时出错

c - 动态分配数组,无需 malloc 和 calloc

c - 使用 realloc C 扩展结构体数组

可以将临时指针数组传递给 C 中的函数吗?

c - 从 c 链接并调用汇编函数

gcc - 编译器如何选择哪个 "get_pc_thunk"函数来获取当前地址?