为什么会出现分段错误?
问题描述:
分段故障发生的原因有哪些? 在下面的代码中,我试图创建一个简单的方法来使用链接列表。 基本上在我的程序中,您只需使用linkedList结构类型创建一个列表。 但是,程序中有一行会导致分段错误。为什么会发生? 任何帮助将不胜感激。谢谢:)为什么会出现分段错误?
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
//Make the struct
typedef struct {
struct node * first;
struct node * current;
}linkedList;
void addNode(linkedList list, int a);
void addFirstNode(linkedList list, int b);
//Function prototypes
int main() {
linkedList list;
addFirstNode(list, 1);
addNode(list, 2);
addNode(list, 3);
addNode(list, 4);
addNode(list, 5);
addNode(list, 6);
addNode(list, 7);
}
void addFirstNode(linkedList list, int input) {
list.first = (struct node *)malloc(sizeof(struct node)); //Make first node
list.first -> num = input; //Fill first node
list.current = list.first;
}
void addNode(linkedList list, int input) {
struct node * newNode = (struct node *)malloc(sizeof(struct node));
newNode -> num = input;
list.current -> next = newNode; //Segmentation fault! (core dumped)
list.current = newNode;
}
答
正如在评论中指出,有许多东西在你的代码来纠正:
- 你需要按引用传递函数的参数(C按值传递的元素) 。
- 你需要初始化你的链表,否则你会试图解引用NULL指针。
下面的代码的正确版本:
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
//Make the struct
typedef struct {
struct node * first;
struct node * current;
}linkedList;
void addNode(linkedList* list, int a);
void addFirstNode(linkedList* list, int b);
//Function prototypes
int main() {
linkedList *list = (struct node *)malloc(sizeof(struct node));;
addFirstNode(list, 1);
addNode(list, 2);
addNode(list, 3);
addNode(list, 4);
addNode(list, 5);
addNode(list, 6);
addNode(list, 7);
}
void addFirstNode(linkedList* list, int input) {
list->first = (struct node *)malloc(sizeof(struct node)); //Make first node
list->first->num = input; //Fill first node
list->current = list->first;
}
void addNode(linkedList *list, int input) {
struct node * newNode = (struct node *)malloc(sizeof(struct node));
newNode->num = input;
list->current->next = newNode; //Segmentation fault! (core dumped)
list->current = newNode;
}
这是代码,导致段故障线路? – satheeshwaran
C没有分段故障的概念。未定义行为的行为 - 按定义 - 未定义。我们不是一个调试服务,阅读[问]。只是:你的功能接口已经坏了。 C严格按价值传递。 – Olaf
[不要在C中输入'malloc'的结果](http://stackoverflow.com/q/605845/995714) –