代码解释

时间:2012-10-03 22:41:31

标签: c winapi

我很难理解这个piece of code

特别是这部分:

     // check that the stuff we wrote has not changed
     if(n[k][0]!=(unsigned char)(n[k]+s[k]+k))
        printf("Error when checking first byte!\n");
     if(s[k]>1 && n[k][s[k]-1]!=(unsigned char)(n[k]-s[k]-k))
        printf("Error when checking last byte!\n");

整个程序试图模仿Windows mallocfree功能。 它必须在Windows上运行。

任何人都可以解释这两个if的工作原理吗?

感谢。

2 个答案:

答案 0 :(得分:4)

通过更多的上下文,代码更有意义。

// used to store pointers to allocated memory
unsigned char *n[NO_OF_POINTERS]; 

int s[5000]; // used to store sizes when testing

....

for(i=0;i<NO_OF_ITERATIONS;i++) {
   k=myrand()%NO_OF_POINTERS; // pick a pointer
   if(n[k]) { // if it was allocated then free it
      // check that the stuff we wrote has not changed
      if(n[k][0]!=(unsigned char)(n[k]+s[k]+k))
         printf("Error when checking first byte!\n");
      if(s[k]>1 && n[k][s[k]-1]!=(unsigned char)(n[k]-s[k]-k))
         printf("Error when checking last byte!\n");
      FREE(n[k]);
   }
   size=randomsize(); // pick a random size
             size=1;
   n[k]=(unsigned char *)MALLOC(size); // do the allocation
   s[k]=size; // remember the size
   n[k][0]=(unsigned char)(n[k]+s[k]+k);  // put some data in the first and
   if(size>1) n[k][size-1]=(unsigned char)(n[k]-s[k]-k); // last byte
}

最后两行使用基于指针值(n[k]),分配大小(s[k])和指针索引的公式将第一个和最后一个字节设置为值( k)。这个公式没有任何意义,它只是计算要存储的值,对于不同的指针分配将是不同的。

您突出显示的if语句检查在释放内存之前,第一个(n[k][0])和最后一个(n[k][s[k]-1])字节的值没有改变。该代码基本上是VirtualAllocVirtualFree函数的测试工具。

答案 1 :(得分:0)

n看起来像unsigned char的多维数组。第一行:

if(n[k][0]!=(unsigned char)(n[k]+s[k]+k))

检查子数组n[k]中的第一个元素是否等于(n[k]+s[k]+k)投射到unsigned char

的总和

第二行:

if(s[k]>1 && n[k][s[k]-1]!=(unsigned char)(n[k]-s[k]-k))

似乎正在检查数组k的{​​{1}}元素是否大于1 AND(逻辑和)子数组s中的元素s[k]-1是不等于n[k]

的结果

总的来说,这是一些非常糟糕的代码,并且可以使用一些更好的变量名称!

相关问题