gpt4 book ai didi

c - 如何更改程序集中的指针值 (x86)

转载 作者:行者123 更新时间:2023-11-30 17:37:49 25 4
gpt4 key购买 nike

这是我的 C 代码,用于更改指针值

     #include<stdio.h>
#include<stdlib.h>
typedef struct tcb tcb_t;

struct tcb {
void* sp;
int id;
};


void* changePointer(struct tcb*);
int main(){
struct tcb* s;
s=malloc(sizeof(struct tcb*));
printf("%p\n",changePointer(s));
printf("%p\n",s);
return 0;
}

这是我的汇编函数(x86)

    .text
.globl changePointer

changePointer:
push %ebp
movl %esp, %ebp
movl 0x8(%ebp),%eax//original pointer value
movl %ebp,%esp
movl %ebp,0x8(%ebp) //it is to be the value after changing
popl %ebp
ret

但它并没有改变汇编函数内的指针值。请解释哪里出了问题?

最佳答案

movl %ebp,%esp

无论你想用这一行做什么:它不会这样工作! EBP 和 ESP 此时具有相同的值,因此该行根本不执行任何操作(否则它将更改堆栈指针,从而导致程序崩溃)!

movl %ebp,0x8(%ebp)

0x8(%ebp) 在这里是错误的:在指令之后,EAX 上方的两行包含指向指针的指针(而不是指针本身)。所以你必须使用 0x0(%eax) 来代替。

但是您希望 eax 包含指针的旧值。对吗?

所以你的代码应该是这样的:

push %ebp
movl %esp, %ebp
movl 0x8(%ebp),%ecx // <-- ecx holds a pointer to the pointer!
movl (%ecx),%eax // <-- eax holds the old value
movl %ebp,(%ecx) // <-- change the pointer
popl %ebp
ret

我还是不明白为什么你要把EBP的值写入指针,因为EBP不包含任何有用的值!

关于c - 如何更改程序集中的指针值 (x86),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278494/

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