一段时间以来,我一直在使用双链表开发一个小的自定义最差 Malloc,虽然这很小,但我认为这会起作用。这段代码有什么明显的问题吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mymal.h"
typedef struct Node
{
int size;
int status;
struct Node *next;
struct Node *previous;
} Node;
Node *endNode;
Node *rootNode;
void *worstfit_mall(int size)
{
Node *theNode = sbrk (size + sizeof(theNode));
void *ptr;
if (rootNode == NULL)
{
theNode->status = 1;
theNode->size = size;
theNode->previous = theNode;
theNode->next = theNode;
rootNode = theNode;
endNode = theNode;
return theNode;
}
Node *worstNode;
worstNode = worstFit(size);
if (worstNode != NULL)
{
theNode->status = 1;
theNode->size = size;
Node *newNode = sbrk((worstNode->size - theNode->size) + sizeof(theNode));
newNode->status = 0;
newNode->size = worstNode->size - theNode->size;
theNode->next = newNode;
theNode->previous = worstNode->previous;
newNode->next = worstNode->next;
return newNode;
}
endNode->next = theNode;
endNode = theNode;
endNode->status = 1;
endNode->size = size;
ptr = sbrk(size + sizeof(theNode));
return ptr;
}
void my_free(void *ptr)
{
Node *pointer;
pointer = (Node*)ptr;
pointer->status = 0;
if ((pointer->next->status == 0) && (pointer->previous->status == 0))
sbrk(-1 * (pointer->next->size + pointer->size));
else if ((pointer->next->status == 1) && (pointer->previous->status == 0))
sbrk(-1 * (pointer->previous->size + pointer->size));
else if ((pointer->next->status == 0) && ( pointer->next->status == 0))
sbrk(-1 * (pointer->previous->size + pointer->next->size + pointer->size));
else
sbrk(-1 * pointer->size);
}
void *worstFit(int size)
{
Node *theNode = rootNode;
Node *worstNode;
while (theNode != NULL)
{
if ((worstNode == NULL || theNode->size > worstNode->size) && (theNode->size >= size) && (theNode->status == 0))
worstNode = theNode;
theNode = theNode->next;
}
return worstNode;
}