我正在研究C中的內存分配器(從零開始重寫malloc和免費)。我使用由mmap創建的堆以及每個內存塊之前的頭部來獲取有關該塊的信息。我用下面的結構來處理我的空閒列表(所有空閒塊的「列表」):Segfault顯然當影響到一個int的值
typedef struct node_t {
long int size;
struct node_t *next;
}node_t;
當分配一個新的內存塊,我使用臨時node_t* temp
。我們也有node_t* startfree
指向我的自由列表的頭。
變量int size
是包含該部分代碼的函數的參數。
bheader_t
是我們稍後會用到的另一種結構。
node_t* temp = (node_t*) (startfree+size+sizeof(bheader_t));
printf("DEBUG : temp %p\n",temp);
printf("DEBUG : startfree %p, size = %ld, next = %p \n",startfree, startfree-> size, startfree -> next);`
printf("DEBUG : future value of temp->size : %ld\n",startfree -> size - size -sizeof(bheader_t));
printf("DEBUG : We want to do temp(%p)->size = startfree(%p)->size (=%ld) - size (=%d) - sizeof(bheader_t) (=%ld)\n", temp, startfree, startfree->size, size, sizeof(bheader_t));
temp -> size = startfree->size - size -sizeof(bheader_t);
printf("DEBUG : temp %p, size : %ld\n",temp,temp->size);
temp -> next = startfree -> next;
startfree = temp;
在某些情況下,進展順利,但在別人,這是我得到什麼(在GDB):
DEBUG : temp 0x7ffff7ff0a0c
DEBUG : startfree 0x7ffff7ef094c, size = 996000, next = (nil)
DEBUG : future value of temp->size : 930452
DEBUG : We want to do temp(0x7ffff7ff0a0c)->size = startfree(0x7ffff7ef094c)->size (=996000) - size (=65536) - sizeof(bheader_t) (=12)
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7bd7a69 in Mem_Alloc_NF (size=65536) at src/nextfit.c:108
108 `temp -> size = startfree->size - size -sizeof(bheader_t);`
段錯誤就簡單int
做作!任何想法可能是什麼?
dat格式。 –
謝謝!無法弄清楚如何很好地做到這一點(我剛開始時忘了4個空格) – BusyAnt
錯誤的地址('0x00007ffff7bd7a69')不對應'temp'('0x7ffff7ff0a0c')或'startfree'(0x7ffff7ef094c ')。 –