【发布时间】:2013-12-05 10:23:54
【问题描述】:
对于有关操作系统功能的课程,我们必须为特定大小的结构编写 malloc/free 实现。我们的想法是将开销(例如我们的代码必须在其中工作的指定(静态)内存块的开始和结束)存储在该块的前几个地址中。
但是,最后一个内存槽的计算出了点问题;我们将所有可用内存插槽的大小添加到第一个可用内存插槽的地址,以确定最后一个插槽是什么。但是,当将int sizeofslots 添加到currentslot 的地址时,实际上是向该地址添加了4 次sizeofslots。以下是相关代码:
/* 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 字节的整数有关,但我们仍然不知道这里发生了什么;谁能解释一下?
【问题讨论】:
-
你知道指针运算是根据指针指向的类型的大小来工作的,对吧? IE。如果您将 1 添加到
int*您将移动到下一个 int,即 4(或 8)个字节,不是下一个字节
标签: c memory-management