The segmentation fault occurs at the point with the comment. I think it has to do with the fact that I'm not initializing the head and tail Nodes. I've tried to initialize the to NULL as well and that didn't work. Unfortunately, I don't really know how to initialize them without using malloc. Any help would be great. Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//the structure of the node in the linked list
typedef struct Node{
int size;
int status;
struct Node* next;
struct Node* previous;
}Node;
int* HEAP_START = 0;
int* HEAP_END = 0;
Node* head;
Node* tail;
int first = 0;
//printf("here1
");
void *my_bestfit_malloc(int size)
{
Node* newNode = NULL;
printf("here2
");
if(first == 0)
{
HEAP_START = (int*)sbrk(0);
newNode = sbrk(size + sizeof(Node));
HEAP_END = (int*)sbrk(0);
head->next = tail; //segmentation error happens here
printf("here3
");
tail->previous = head;
newNode->size = size;
newNode->status = 1;
first++;
}
else
{
Node* currNode = head->next;
printf("here4
");
while(currNode->next != tail)
{
if(currNode->size == size)
{
newNode = currNode;
currNode->previous->next = currNode->next;
currNode->next->previous = currNode->previous;
newNode->size = size;
newNode->status = 1;
printf("here5
");
break;
}
else
{
currNode = currNode->next;
printf("here6
");
}
}
if(currNode->next == tail)
{
newNode = sbrk(size + sizeof(Node));
HEAP_END = (int*)sbrk(0);
newNode->size = size;
newNode->status = 1;
printf("here7
");
}
}
return newNode + sizeof(Node);
}
int main()
{
typedef struct person{
int age;
char sex;
}person;
printf("main1
");
person* dave = (person*)my_bestfit_malloc(sizeof(person));
printf("main2
");
person* vicki = (person*)my_bestfit_malloc(sizeof(person));
printf("main3");
person* alex = (person*)my_bestfit_malloc(sizeof(person));
dave->age = 26;
dave->sex = 'M';
vicki->age = 24;
vicki->sex = 'F';
alex->age = 19;
alex->sex = 'F';
printf("Dave:
Age: %d
Sex: %c
", dave->age, dave->sex);
printf("Vicki:
Age: %d
Sex: %c
", dave->age, dave->sex);
printf("Alex:
Age: %d
Sex: %c
", dave->age, dave->sex);
}
So I tried changing my Node* head and tail to: Node head; Node tail; instead, but received these errors:
mymalloc.c: In function ‘my_bestfit_malloc’:
mymalloc.c:38: error: invalid type argument of ‘->’ (have ‘Node’)
mymalloc.c:40: error: invalid type argument of ‘->’ (have ‘Node’)
mymalloc.c:47: error: invalid type argument of ‘->’ (have ‘Node’)
mymalloc.c:49: error: invalid operands to binary != (have ‘struct Node *’ and ‘Node’)
mymalloc.c:67: error: invalid operands to binary == (have ‘struct Node *’ and ‘Node’)
I understand the first three, I need to use head.next = tail; instead, but I don't understand the last two.
Final edit:
Got if figured out. The pointers for head and tail need to be actual Node structs instead of struct pointers. Also I needed to return a void pointer instead of a Node.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…