我正在实现malloc的一个版本,并且是免费的。所以,我有一个固定长度(10000)的静态char数组。然后,我实现了一个struct memblock,它保存了块的大小等信息,如果它是空闲的。。。
我实现malloc的方式是将小的块(这是我的代码:

#define MEMSIZE 10000 // this is the maximum size of the char * array
#define BLOCKSIZE sizeof(memblock) // size of the memblock struct

static char memory[MEMSIZE]; // array to store all the memory
static int init; // checks if memory is initialized
static memblock root; // general ptr that deals with both smallroot and bigroot
static memblock smallroot, bigroot; // pointers to storage of small memory blocks and bigger blocks


void initRoots(size_t size, char* fileName, int lineNum)
{
  smallroot = (memblock)memory;
  smallroot->prev = smallroot->next = 0;
  smallroot->size = MEMSIZE - 2 * BLOCKSIZE;
  smallroot->isFree = 1;
  smallroot->file = fileName;
  smallroot->lineNum = lineNum;

  bigroot = (memblock)(((char *)memory) + MEMSIZE - BLOCKSIZE - 1);
  bigroot->prev = bigroot->next = 0;
  bigroot->size = MEMSIZE - 2 * BLOCKSIZE;
  bigroot->isFree = 1;
  bigroot->file = fileName;
  bigroot->lineNum = lineNum;
  init = 1;
}

我使用GDB来查看我在哪里遇到Seg错误。执行bigroot->next=0;时会发生这种情况。这会以某种方式将smallroot设置为0。更奇怪的是什么?如果我设置bigroot->next=0x123,那么smallroot变成0x1。如果设置0x1234,则它将变为0x12。它正在将smallroot设置为bigroot->next的值,不包括其最后两位。我真的不明白这是怎么回事!
这是memblock的定义:
typedef struct memblock_* memblock;

struct memblock_ {
  struct memblock_ *prev, *next;  // pointers to next and previous blocks
  /* size: size of allocated memory
    isFree: 0 if not free, 1 if free
    lineNum: line number of user's file where malloc was invoked
  */
  size_t size, isFree, lineNum;
  char* file; // user's file name where the block was malloced
};

最佳答案

#define BLOCKSIZE sizeof(memblock) // size of the memblock struct
你想要:

#define BLOCKSIZE sizeof(*memblock) // size of the memblock_ struct

这里的-1也是假的(创建了错误对齐的指针):
bigroot = (memblock)(((char *)memory) + MEMSIZE - BLOCKSIZE - 1);

实际上,我将指向memblock的指针存储在内存数组中。memblock的值存储在stack中。
不,他们不是。smallrootbigroot清楚地指向数组本身。

08-25 02:51