【发布时间】:2015-10-16 04:14:44
【问题描述】:
到此为止,我已经不知所措了。让这段代码(大部分)正常工作后。我通过执行“gcc -o selfRef selfRef.o”而不是“gcc -c selfRef.c”来编译它不确定编译C文件的正确方法是什么,但我开始收到分段错误错误,我似乎无法弄清楚如何解决它。
我在我的插入方法中插入了打印语句,所以我知道代码在中断之前甚至没有调用它。知道如何解决这个问题吗?
谢谢
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node
{
int value;
struct Node *next;
};
struct Node *head;
int main( int argc, char* argv[] )
{
#define True 1
#define False 0
typedef int Boolean;
struct Node *head = NULL;
int i;
printf("Your linked list:\n");
//inserts items into the list
for (i = 1; i < 20; i += 2)
{
insert(i,&head);
}
printList(head);
}
insert(int x, struct Node **pL)
{
printf("Inserts");
if(*pL == NULL)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
(*pL) = temp;
(*pL) -> value = x;
(*pL) -> next = NULL;
}
else
{
insert(x,&((*pL) -> next));
printf("Inserts");
}
}
delete(int x, struct Node **pL)
{
if(*pL == NULL)
{
if(((*pL) -> value) == x)
{
(*pL) = (*pL) -> next -> next;
}
else
{
lookup(x, head -> next);
}
}
}
lookup(int x, struct Node *head)
{
if(head -> next == NULL)
{
return;
}
else if(head -> value == x)
{
return True;
}
lookup(x,(head) -> next);
}
printList(struct Node *head)
{
if(head == NULL)
{
printf("The list is empty");
return;
}
printf("Node: %s",head -> value);
printList(head -> next);
}
【问题讨论】:
-
您是否尝试过使用 valgrind 或其他工具来确定段错误发生的位置?这肯定会帮助您找到原因并可能解决问题。
-
if(*pL == NULL) { if(((*pL) -> value) == x)是错误的。和lookup(x, head -> next);,不使用全局变量head。 -
@BLUEPIXY 第一个东西是临时测试的东西 // 代码是实际进入该方法的内容。
-
您应该使用
gcc -Wall -Wextra -g进行编译,然后使用调试器 (gdb)。请注意,修复我损坏的代码问题在这里是题外话。
标签: c