您的位置:首页 > 理论基础

【深入理解计算机系统-第二版】3.66习题

2013-04-07 09:32 567 查看
题目:

You are charged with maintaining a large C program, and you come across the following code:

typedef struct {
  int left;
  a_struct a[CNT];
  int right;
} b_struct;

void test(int i, b_struct *bp)
{
  int n = bp->left + bp->right;
  a_struct *ap = &bp->a[i];
  ap->x[ap->idx] = n;
}


000000 <test>:
0:    55                        push   %ebp
1:    89 e5                     mov    %esp,%ebp
3:    53                        push   %ebx
4:    8b 45 08                  mov    0x8(%ebp),%eax ;%eax=i
7:    8b 4d 0c                  mov    0xc(%ebp),%ecx ;%ecx=bp
a:    8b d8 1c                  imul   $0x1c,%eax,%ebx ;%ebx=i*28
d:    8d 14 c5 00 00 00 00      lea    0x0(,%eax,8),%edx ;%edx=8i;
14:    29 c2                    sub    %eax,%edx ;%edx=7i;
16:    03 54 19 04              add    0x4(%ecx,%ebx,1),%edx ;%edx=7i+[bp+28i+4]
1a:    8b 81 c8 00 00 00        mov    %0xc8(%ecx),%eax ;%eax=right
20:    03 01                    add    (%ecx),%eax  ;%eax=right+left
22:    89 44 91 08              mov    %eax,0x8(%ecx,%edx,4) ;[bp+4*7i+4*[bp+28i+4]+0x8]=%eax
26:    5b                       pop    %ebx
27:    5d                       pop    %ebp
28:    c3                       ret


答案:

  其中,汇编代码中的关键语句都加上了注释,读者可自行推导,然后与我的注释对比一下。注释中,中括号的意思是取该地址所存的值。

  注意第22行,bp+4*7i+4*[bp+28i+4]+0x8=bp+4+28i+4*[bp+28i+4]+4。这个地址就是ap->x[ap->idx]。bp+4是a[CNT]的首地址,bp+28i+4可以看作是ap->idx。那么我们就很容推出sizeof(a_struct)大小为28bytes。在a_struct中,idx的偏移为0。而b.struct.a.struct.x[]偏移为(bp+4+28i)+4,也进一步证明了sizeof(a_struct)的大小为28bytes。right在b_struct中的偏移0xc8,也就是十进制的200,而a[CNT]的偏移为4,则数组的总大小为196,196/28=7,则CNT=7。

  a_struct的大小为28bytes,idx的大小为4byte,剩下来24bytes都被x数组所占用,故x数组中有6个元素。它的结构是:

struct {
int idx;
int x[6];
}a_struct;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: