为什么我的链接列表程序会给出SIGSEGV?

时间:2014-10-16 10:17:32

标签: c linux linked-list

我正在创建一个简单的链表程序来插入和查看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;
}

1 个答案:

答案 0 :(得分:2)

  1. sizeof占用结构长度,在32位架构
  2. 的情况下,总是传递4个字节
  3. 用于迭代temp节点的while循环是错误的,您应该检查next节点是否为NULL