这是我的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但是它没有改变汇编函数.Please内部的指针值,解释哪里出错了?
发布于 2014-03-09 15:40:17
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不包含任何有用的值!
发布于 2014-03-12 01:12:54
试试这个,它只使用一条汇编指令,并将样板留给编译器:
void changePointer(struct tcb *s)
{
asm("movl %%esp, %0"
: /* No output */
: "m" (s->sp);
: /* Nothing clobbered */
);
}https://stackoverflow.com/questions/22278494
复制相似问题