繁体   English   中英

组装中的指针

[英]Pointers in Assembly

我在教科书上遇到练习上的问题。 我必须填写下面显示的C代码的缺失部分:

int switch3(int *p1, int *p2, int action)
{
    int result = 0;
    switch(action) {
    case 1:
     // Fill in
    case 2:
     // Fill in
    default:
     // Fill in
}
     return result;
}

我遇到麻烦的原因是因为使用了指针。 我很确定我知道它们是如何工作的,但让我详细说明。 本书为我们提供了以下IA32程序集,其中带有注释。

Arguments: p1 at %ebp+8, p2 at %ebp+12, action at %ebp+16
 Registers: result in %edx (initialized to -1) The jump targets:

.L13 // case(1)
  movl  8(%ebp), %eax // eax = p1
  movl  (%eax), %edx  // result = *p1
  movl  12(%ebp), %ecx // ecx = p2
  movl  (%ecx), %eax   // eax = *p2
  movl 8(%ebp), %ecx  // ecx = p1 
  movl %eax, (%ecx)   // *p1 = *p2

因此,最后是result = * p1和* p1 = * p2我认为这是正确的,但是接下来是什么使我感到困惑。

.L14 //case(2)
   movl  12(%ebp), %edx // result = p2  which is not possible because p2 is a pointer and result is an int
   movl  (%edx), %eax  
  movl   %eax, %edx
  movl    8(%ebp), %ecx
  addl (%ecx), %edx
  movl  12(%ebp), %eax
  movl  %edx, (%eax)
  jmp  .L19

 .L19 // default
    movl %edx, %eax

谁能为我解决这个问题?

.L14 //case(2)
  movl  12(%ebp), %edx // result = p2  which is not possible because 
                       // p2 is a pointer and result is an int

您的评论result = p2是错误的。 edx在整个函数过程中均edx result约束。 您唯一知道的是函数退出后, result存储在edx (此外,即使与您的问题没有直接关系,程序集也没有超出其大小的类型的概念,因此寄存器不知道它是保存指针还是整数。)

所以:

.L14 //case(2)
  movl  12(%ebp), %edx   // edx = p2
  movl  (%edx), %eax     // eax = *p2
  movl   %eax, %edx      // edx = eax ( = *p2 )
  movl    8(%ebp), %ecx  // ecx = p1
  addl (%ecx), %edx      // edx = edx + *p1 ( = *p1 + *p2 )
  movl  12(%ebp), %eax   // eax = p2
  movl  %edx, (%eax)     // *p2 = edx ( = *p1 + *p2 )
  jmp  .L19              // if .L19 is the end of the function, then you now know
                         // that result = *p1 + *p2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM