的節點被定義如下:該程序爲什麼分配8個頁面,但只能容納2048個大小爲8個字節的節點?
struct node{
int value;
struct node *next;
};
通過使用sizeof(struct node)
我得知一個節點是8個字節(在XV6)。所以我用malloc
來分配一些內存空間來存儲一些節點。 xv6中的單個頁面是4096個字節,如果我有8個頁面,則可以存儲4096個這樣的節點。但是,那不是發生了什麼事情,在這樣的節點之後,如果另一個節點,更多的頁面被分配給當前進程,爲什麼會這樣呢?
// Now display how many pages are allocated to the process
// Suppose there is a system call named memcount(), it is given by
// my professor, I wouldn't think there's any problem with that
//
memcount(); // which prints 3, meaning that initially, without
// allocaing anything, 3 pages = 12288 bytes of memory allocated
for(i = 0; i < 2048; ++i){
struct node *nd = (struct node *)malloc(sizeof(struct node));
}
memcount(); // which prints 11, so 8 more pages are allocated
// If we allocated 1 more node
struct node *nd = (struct node *)malloc(sizeof(struct node));
memcount(); // which prints 19, another 8 pages are allocated
這就是我非常困惑的地方,不應該在前8頁剩下很多空間嗎?由於單個節點的大小隻有8個字節,爲什麼會有更多的頁面分配給進程?
'malloc(X)'使用多於'X'字節的內存。一些內存被隱藏地分配給堆控制結構。 – DyZ
通常,當您分配少量內存時,實際上可能會保留比您指定的更多的內存(系統可能具有分配的最小大小,或者堅持兩個分配大小或其他類似的功能)。保留已分配塊的詳細信息可能會產生額外的開銷,這會使用您要求的部分之外的空間。 – Dmitri
@Dmitri,謝謝。我明白'malloc(n)'使用的字節數多於'n'字節,但是這應該是正確的?這是怎麼發生的?我編輯了這篇文章,我認爲這更清楚地解釋了 –