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


    题目:


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

     1 typedef struct {
     2   int left;
     3   a_struct a[CNT];
     4   int right;
     5 } b_struct;
     6 
     7 void test(int i, b_struct *bp)
     8 {
     9   int n = bp->left + bp->right;
    10   a_struct *ap = &bp->a[i];
    11   ap->x[ap->idx] = n;
    12 }
     1 000000 <test>:
     2 0:    55                        push   %ebp    
     3 1:    89 e5                     mov    %esp,%ebp
     4 3:    53                        push   %ebx
     5 4:    8b 45 08                  mov    0x8(%ebp),%eax ;%eax=i
     6 7:    8b 4d 0c                  mov    0xc(%ebp),%ecx ;%ecx=bp
     7 a:    8b d8 1c                  imul   $0x1c,%eax,%ebx ;%ebx=i*28
     8 d:    8d 14 c5 00 00 00 00      lea    0x0(,%eax,8),%edx ;%edx=8i;
     9 14:    29 c2                    sub    %eax,%edx ;%edx=7i;
    10 16:    03 54 19 04              add    0x4(%ecx,%ebx,1),%edx ;%edx=7i+[bp+28i+4]
    11 1a:    8b 81 c8 00 00 00        mov    %0xc8(%ecx),%eax ;%eax=right
    12 20:    03 01                    add    (%ecx),%eax  ;%eax=right+left
    13 22:    89 44 91 08              mov    %eax,0x8(%ecx,%edx,4) ;[bp+4*7i+4*[bp+28i+4]+0x8]=%eax
    14 26:    5b                       pop    %ebx
    15 27:    5d                       pop    %ebp
    16 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个元素。它的结构是:

    1 struct {
    2        int idx;
    3        int x[6];
    4 }a_struct;


    作者:Chenny Chen
    出处:http://www.cnblogs.com/XjChenny/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    MVC3 缓存应用
    centos下安装tomcat
    VS2010安装完SP1后再安装Silverlight Tools 4遇到的问题解决办法
    TOMCAT多站点配置
    C#.NET 添加图片水印
    装了vs11后运行MVC3程序出问题
    ASP.NET Session的七点认识
    C# 用正则取文本中所有链接
    Long time no blog...
    从程序员到项目经理(二)
  • 原文地址:https://www.cnblogs.com/XjChenny/p/3003406.html
Copyright © 2020-2023  润新知