我正在创建一个简单的链表程序来插入和查看LL的元素。当我尝试插入第二个元素时,它会给出SIGSEV,但我无法理解为什么?? !!
请帮我指出问题:
的main.c :
#include <stdio.h>
#include <stdlib.h>
typedef struct linkedList{
int data;
struct linkedList *next;
}LL;
LL *start;
int main(){
int option = 0;
while(1){
printf("Enter option: \n");
scanf("%d", &option);
switch(option){
case 1:
addNode(start);
break;
case 2:
readNodes(start);
break;
case 3:
exit(0);
}
}
}
插入节点:
int addNode(LL *startNode){
LL *temp, *node;
int data = 0;
printf("Enter data: ");
scanf("%d", &data);
if(startNode == NULL){/*Application only when the first element is inserted*/
startNode = (LL*)malloc(sizeof(LL*));
if(startNode == NULL){
printf("Error: Memory not allocated!!\n");
exit(1);
}
startNode->data = data;
startNode->next = NULL;
start = startNode;
return 0;
}
temp = startNode;
while(temp != NULL){
temp = temp->next;
}
node = (LL*)malloc(sizeof(LL*));
node->data = data;
node->next = NULL;
temp->next = node;
temp = temp->next;
return 0;
}
答案 0 :(得分:2)
sizeof
占用结构长度,在32位架构temp
节点的while循环是错误的,您应该检查next
节点是否为NULL
。