【发布时间】:2015-03-21 20:47:35
【问题描述】:
分段错误发生在有注释的点。我认为这与我没有初始化头部和尾部节点这一事实有关。我也尝试将其初始化为 NULL,但没有成功。不幸的是,我真的不知道如何在不使用 malloc 的情况下初始化它们。任何帮助都会很棒。谢谢。
#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\n");
void *my_bestfit_malloc(int size)
{
Node* newNode = NULL;
printf("here2\n");
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\n");
tail->previous = head;
newNode->size = size;
newNode->status = 1;
first++;
}
else
{
Node* currNode = head->next;
printf("here4\n");
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\n");
break;
}
else
{
currNode = currNode->next;
printf("here6\n");
}
}
if(currNode->next == tail)
{
newNode = sbrk(size + sizeof(Node));
HEAP_END = (int*)sbrk(0);
newNode->size = size;
newNode->status = 1;
printf("here7\n");
}
}
return newNode + sizeof(Node);
}
int main()
{
typedef struct person{
int age;
char sex;
}person;
printf("main1\n");
person* dave = (person*)my_bestfit_malloc(sizeof(person));
printf("main2\n");
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:\n\tAge: %d\n\tSex: %c\n", dave->age, dave->sex);
printf("Vicki:\n\tAge: %d\n\tSex: %c\n", dave->age, dave->sex);
printf("Alex:\n\tAge: %d\n\tSex: %c\n", dave->age, dave->sex);
}
所以我尝试将我的 Node* 头部和尾部更改为:Node head;节点尾;相反,但收到以下错误:
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’)
前三个我明白了,我需要用head.next = tail;相反,但我不明白最后两个。
最终编辑: 想通了就知道了。 head 和 tail 的指针需要是实际的 Node 结构而不是结构指针。我还需要返回一个 void 指针而不是一个节点。
【问题讨论】:
-
您是否尝试过跟踪所有指针以确保它们指向您认为它们应该使用调试器的位置?
-
你没有分配到 head:它应该指向哪里?你在什么环境下写作? Malloc 通常由操作系统实现。
-
如果你创建一个指向它的指针,你负责用 malloc 分配内存。如果您创建一个“普通”变量(不是指针),编译器会在堆栈上为其分配空间。所以使用“节点头,尾;”而不是“节点 *head, *tail;”。
-
你搞清楚了吗?
-
@Chimera:是的!抱歉忘记发了,正在整理中。问题是头和尾的节点需要是节点对象而不是节点指针。另外,我需要返回一个 void 指针,而不是一个节点。
标签: c linked-list segmentation-fault malloc nodes