Malloc Lab的realloc功能不起作用

时间:2014-11-14 19:45:49

标签: c malloc

注意:这是学校作业

我在malloc lab上实现realloc()函数时遇到很大麻烦。我正在使用一个非常简单的显式空闲列表。到目前为止,除了realloc()之外我还有一切工作。在跟踪文件上,realloc()大约是1/4,并且失败。问题是我似乎无法重现为什么realloc()在gdb中失败。

void *find_fit(size_t);
void print_heap();

typedef struct header {
    size_t size;
    struct header *n_ptr;
    struct header *p_ptr;
} header_block;

/* 
 * mm_init - initialize the malloc package.
 */
int mm_init(void)
{
    header_block *p = mem_sbrk(HEADER_BLOCK_SIZE);
    p->size = HEADER_BLOCK_SIZE;
    p->n_ptr = p;
    p->p_ptr = p;
    return 0;
}

/* 
 * mm_malloc - Allocate a block by incrementing the brk pointer.
 *     Always allocate a block whose size is a multiple of the alignment.
 */
void *mm_malloc(size_t size)
{
    int nsize = ALIGN(HEADER_BLOCK_SIZE + size);
    header_block *bp = find_fit(nsize);
    if (bp == NULL) {
        bp = mem_sbrk(nsize);
        if (bp == (void *)-1)
            return NULL;
        else {
            bp->size = nsize; //set size to new size and set allocated
            bp->size |= 1;
        }
    } else {
        bp->size |= 1; //If find fit, mark as allocated
        bp->p_ptr->n_ptr = bp->n_ptr;
        bp->n_ptr->p_ptr = bp->p_ptr;
    }
    return (char *) bp + HEADER_BLOCK_SIZE;

}

void *find_fit(size_t size) {
    header_block *p;
    p = ((header_block *)mem_heap_lo())->n_ptr;
    while (p != mem_heap_lo() && p->size < size) {
        p = p->n_ptr;
    }
    if (p == mem_heap_lo()) {
        return NULL;
    } else {
        return p;
    }

}


void mm_free(void *ptr)
{
    header_block *bp = ptr-HEADER_BLOCK_SIZE;
    header_block *head = mem_heap_lo();
    bp->size = bp->size & ~1;
    bp->p_ptr = head;
    bp->n_ptr = head->n_ptr;
    bp->n_ptr->p_ptr = bp;
    head->n_ptr = bp;
}

/*
 * mm_realloc - Implemented simply in terms of mm_malloc and mm_free
 */
void *mm_realloc(void *ptr, size_t size) #failing
{
    header_block *bp = ptr - HEADER_BLOCK_SIZE;
    void *newptr = mm_malloc(size);
    if (newptr == NULL) {
        return NULL;
    } 
    int copysize = bp->size - HEADER_BLOCK_SIZE;
    if (size < copysize) {
        copysize = size;
    }
    memcpy(newptr, ptr, copysize);
    mm_free(ptr);
    return newptr;
}

跟踪文件中的错误表明realloc()失败,因为mem_sbrk()(提供给我们的虚拟堆扩展器功能)失败。

我为张贴这么多代码而道歉。我试过调试,盯着这个很长一段时间。任何帮助将不胜感激!

0 个答案:

没有答案