【发布时间】:2023-03-21 00:15:01
【问题描述】:
我正在实现一个 malloc 版本并且可以免费练习。所以,我有一个固定长度(10000)的静态字符数组。然后,我实现了一个 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 Fault。它发生在 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
};
【问题讨论】:
-
您的意思是最后 2 个半字节或最后一个字节。不是最后 2 位。
-
能否请您添加
memblock的定义,否则很难判断。 -
你真的应该关心对齐。
-
对齐是什么意思?如果有人想要整个源,我可以发布一个链接。我真的不明白为什么会这样。