我试图在C中实现我自己的malloc()
函数,但是我正面临着这个问题。前两个分配的地址是正确的,但在此之后,它不显示其他地址。我的意思是,它陷入了无限循环。但是,如果我删除条件&& ptr->size > BLK_SIZE
,它似乎工作。所以,问题是,为什么这种情况会破坏代码?这怎么可能通过除了解除条件以外的其他方式解决?定制malloc中的无限循环()
这里是我的代码...
/* Author : Singh*/
typedef struct block_header {
unsigned int size : 29,
zero : 2,
alloc : 1;
} block_header;
//macros
#define HEADER_BLK_SIZE sizeof(block_header) // 4 bytes header
#define ALIGNED_PAYLOAD_SIZE (((((size)-1)>>2)<<2)+4) //to align the payload
#define BLK_SIZE HEADER_BLK_SIZE + ALIGNED_PAYLOAD_SIZE //total size of a blk
#define HEAP_EXTEND_SIZE ((BLK_SIZE)*1024) //the total heap size
static void *base_heap = NULL; //base of the heap, starting point
static void *end_heap = NULL;
static block_header *freeblk = NULL;
void *mymalloc(size_t size) {
size_t remainder_heap = (HEAP_EXTEND_SIZE) - (BLK_SIZE);
// first time init the heap and allocate the first block
if (!base_heap) {
base_heap = sbrk(0);
end_heap = sbrk(HEAP_EXTEND_SIZE);
if (base_heap == (void*)-1 || end_heap == (void*)-1)
return NULL;
block_header *blk = (block_header*)base_heap;
blk->size = BLK_SIZE;
blk->zero = 2;
blk->alloc = 1;
freeblk = ((void*)(base_heap)) + BLK_SIZE;
freeblk->size = remainder_heap;
freeblk->zero = 2;
freeblk->alloc = 0;
return ((void*)blk) + HEADER_BLK_SIZE;
} else
if (size >= HEAP_EXTEND_SIZE) {
return NULL;
} else {
//second time and the others
block_header *ptr = (block_header*)base_heap;
size_t i;
i = 0;
while (i < (HEAP_EXTEND_SIZE)) { //travel the heap
if ((ptr->alloc) ==1) { //if it's allocate we go to the nxt block
ptr = ((void*)ptr) + ((size_t)(ptr->size));
i += ((size_t)(ptr->size));
} else
if ((ptr->alloc) == 0 && ptr->size > BLK_SIZE) { /*if it's free and
big enough */
ptr->size = BLK_SIZE;
ptr->zero = 2;
ptr->alloc = 1;
return ((void*)ptr) + (HEADER_BLK_SIZE);
} else { //not big enough so we go to the next block
ptr = ((void*)ptr) + ((size_t)(ptr->size));
i += ((size_t)(ptr->size));
}
}
return NULL; //if it does not wok
}
}
//for testing my code
void main() {
int *i =(int*)mymalloc(12);
printf("pointeur i : %p\n", i);
int *ii = (int*)mymalloc(16);
printf("pointeur ii : %p\n", ii);
int *iii = (int*)mymalloc(20);
printf("pointeur iii : %p\n", iii);
int *iiii = (int*)mymalloc(24);
printf("pointeur iiii : %p\n", iiii);
}