- 很顯然,初始指針到這個空間必須以某種方式遞增時調用get_memory()製成,而新指針會返回到調用進程。我如何通過特定數量的字節增加指針?
當你調用get_memory()
,你會返回一個指向加入一些抵消主存儲器。單詞'增量'意味着你將改變初始指針的值,你不應該這樣做。
下面是一些簡單的代碼,我subaddressing一個大的內存塊。
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
// Allocate a block of memory
void * memory_block = malloc (512);
// Now "Split" that memory into two halves.
void * first_half = memory_block;
void * second_half = memory_block + 256;
// We can even keep splitting...
void * second_first_half = second_half;
void * second_second_half = second_half + 128;
// Note that this splitting doesn't actually change the main memory block.
// We're just bookmarking locations in it.
printf ("memory_block %p\n", memory_block);
printf ("first_half %p\n", first_half);
printf ("second_half %p\n", second_half);
printf ("second_first_half %p\n", second_first_half);
printf ("second_second_half %p\n", second_second_half);
return 0;
}
- 我理解,對於每種塊大小自由列表必須被保留,但是我不能確定究竟如何這些將被初始化和維護。什麼是完全存儲在空閒列表中?內存指針?
至少,你可能要跟蹤內存指針和該內存塊的大小,所以像這樣的......
typedef struct memory_block {
void * memory;
size_t size;
} memory_block_t;
還有其他的方法來表示這雖然。例如,您通過跟蹤其相對於全局malloc的內存偏移量來獲得等效信息。我建議將存儲器視爲一組偏移量,如下所示:
void * global_memory; // Assigned by start_memory()
// Functionally equivalent to the above struct
// memory = global_memory + begin;
// size = end - begin;
typedef struct memory_block {
size_t begin;
size_t end;
} memory_block_t;
這個難題有多種解決方法。