C中的自定义Malloc - 分段错误

时间:2018-04-11 07:53:00

标签: c linked-list segmentation-fault malloc doubly-linked-list

我正在尝试使用最适合的分配来创建malloc()函数。我使用双向链表来实现内存块的数据结构。

每个块由标题和数据组成。但是当我运行它时,我的程序一直给我一个分段错误(核心转储)。

我的部分代码如下:

typedef struct Node{ 
    unsigned int size; 
    int flag; // free is 1 and used is 0
    struct Node* next;
    struct Node* prev; 
}Node;

Node* head = NULL;
Node* tail = NULL;

Node* find_best_fit(unsigned int size){
    size += sizeof(Node);
    Node* curr;
    curr = head;
    Node* best_fit = NULL;
    while (curr != NULL){
        if((curr->flag) && (curr->size >= size) && (best_fit == NULL || curr->size < best_fit->size)){
            best_fit = curr;
            if(best_fit->size == size){
                break;
            }
        }
        curr = curr->next;
    }
    return best_fit;
}


void* my_malloc(unsigned int size)
{
    if(size == 0)
        return NULL;

    Node* best = NULL;
    Node* current_node = NULL;
    Node* temp_node = NULL;
    Node* rem = NULL;

    if(head == NULL){
        head = (Node*)sbrk(size + sizeof(Node));
        head->flag = 0;
        head->prev = NULL;
        head->next = NULL;
        head->size = size;
        tail = head;
        return (head + sizeof(Node));
    } else{
        best = find_best_fit(size);
        if(best == NULL){
            current_node = (Node*)sbrk(size + sizeof(Node));
            temp_node->prev = tail;
            temp_node->next = NULL;
            temp_node->size = size + sizeof(Node);
            temp_node->flag = 0;
            current_node = temp_node;
            tail->next = current_node;
            tail = current_node;
            return (void*)(current_node + sizeof(Node));
        } else{
            current_node = (Node*)(best+size);
            rem->size = best->size - size - sizeof(Node);
            rem->flag = 1;
            rem->next = best->next;
            rem->prev = best;
            current_node = rem;
            current_node->next->prev = current_node;
            best->size = size + sizeof(Node);
            best->flag = 0;
            best->next = current_node;
            return (void*)(best + sizeof(Node));
        }
    }
}

0 个答案:

没有答案