将“int”添加到地址会导致int被添加4次

时间:2013-12-05 10:23:55

标签: c memory-management

对于有关操作系统功能的课程,我们必须为特定大小的结构编写malloc / free实现。我们的想法是在该块的前几个地址中存储开销,例如我们的代码必须工作的指定(静态)内存块的开始和结束。

然而,最后一个内存插槽的计算出了问题;我们将所有可用内存插槽的大小添加到第一个可用内存插槽的地址,以确定最后一个插槽是什么。但是,将int sizeofslots添加到currentslot的地址时,实际上会向此地址添加sizeofslots 4次。这是相关的代码:

/* Example memory block*/
/* |------------------------------------------------------------------------------|*/
/* | ovr | 1 t | 0   | 1 t | 1 t | 1 t | 0   | 0   | 0   | 0   | 0   | 0   | 0   |*/
/* |------------------------------------------------------------------------------|*/
/* ovr: overhead, the variables `currentslot`, `firstslot` and `lastslot`.        
 * 1/0: Whether or not the slot is taken.      
 * t: the struct 
 */

/* Store the pointer to the last allocated slot at the first address */
currentslot = get_MEM_BLOCK_START();
*currentslot = currentslot + 3*sizeof(void *);

/* The first usable memory slot after the overhead */
firstslot = currentslot + sizeof(void *);
*firstslot = currentslot + 3*sizeof(void *);

/* The total size of all the effective memory slots */
int sizeofslots = SLOT_SIZE * numslots;

/* The last usable slot in our memory block */
lastslot = currentslot + 2*sizeof(void*);
*lastslot = firstslot + sizeofslots;
printf("%p + %i = %p, became %p\n", previous, sizeofslots, previous + (SLOT_SIZE*numslots), *lastslot);

我们认为它与4字节的整数有关,但我们仍然没有得到这里发生的事情;谁能解释一下呢?

3 个答案:

答案 0 :(得分:3)

C的指针算法总是这样工作;加法和减法始终是指向的项目,以字节为单位。

将它与数组索引进行比较:您可能知道,对于任何指针a[i]和整数*(a + i),表达式a等效于i。因此,必须根据a的每个元素的大小进行添加。

要解决此问题,请在添加之前将结构指针向下转换为(char *)

答案 1 :(得分:2)

当你向指针添加一个整数时,它会增加许多步幅(即myPointer + x将增加x*sizeof(x)。如果没有发生这种情况,则可能有未对齐的整数,这就是许多处理器架构是一个错误,至少可以说会引起一些时髦的行为。

以下面的例子为例

char* foo = (char*)0x0; // Foo = 0
foo += 5;               // foo = 5

short* bar = (short*)0x0; // Bar = 0; (we assume two byte shorts)
bar += 5;                 // Bar = 0xA (10)

int* foobar = (int*)0x0;  // foobar = 0; (we assume four byte ints)
foobar += 2;              // foobar = 8; 

char (*myArr)[8];         // A pointer to an array of chars, 8 size
myArr += 2;               // myArr = 0x10 (16). This is because sizeof(char[8]) = 8;

答案 2 :(得分:1)

Example

const int MAX = 3;

int main ()
{
   int  var[] = {10, 100, 200};
   int  i, *ptr;

   /* let us have array address in pointer */
   ptr = var;
   for ( i = 0; i < MAX; i++)
   {

      printf("Address of var[%d] = %x\n", i, ptr );
      printf("Value of var[%d] = %d\n", i, *ptr );

      /* move to the next location */
      ptr++;
   }
   return 0;
}

输出:

Address of var[0] = bfb7fe3c
Value of var[0] = 10
Address of var[1] = bfb7fe40
Value of var[1] = 100
Address of var[2] = bfb7fe44
Value of var[2] = 200

您可以从示例中推断出,指针将自身增加“Number Of Bytes”=“它指向的类型的大小”。在这里,Number Of bytes = sizeof(int)。类似地,在char的情况下,它将自己增加1个字节。