奇怪的C堆栈内存覆盖

Weird C stack memory overrides

本文关键字:内存 覆盖 堆栈      更新时间:2023-10-16

我正在实现一个版本的malloc和免费练习。因此,我有一个固定长度(10000)的静态字符数组。然后,我实现了一个struct memblock,它保存了块的大小等信息,如果它是空闲的…

我实现malloc的方式是这样的,我把小块(<8字节)放到char数组的前面,大一点的放到另一端。所以,我基本上是用两个链表来连接前面和后面的块。然而,我在初始化列表时遇到了奇怪的问题(在第一次调用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来查看我在哪里得到segfault。当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的值存储在栈中

不,他们不是。smallrootbigroot 明显指向数组本身。