具有链表的分段错误(singal 11 sigsegv)

时间:2016-11-29 05:11:21

标签: c linked-list sigsegv cs50

在pset5之前使用链接列表和指针编写程序以进行练习,并留下两个我无法解决的内存错误。

#include <stdio.h>
#include <stdlib.h>

//define struct for Nodes
typedef struct list
{
    int data;
    int key;
    struct list* next;
}Node;

//function declarations
Node* create(int a, int *counter);
void insert(int a, int *counter);
void delete_list();
void printlist();


//global pointers
Node* Head = NULL;
Node* Current = NULL;


int main()
{
    int *keycounter =(int*)malloc(sizeof(int));
    int value = 20;
    keycounter = 0;
    Head=create(value, keycounter);
    value = 30;
    insert(value, keycounter);
    value = 40;
    insert(value, keycounter);
    printlist();
    delete_list();

    free(keycounter);
    return 0;
}
// VV functions VV
void delete_list()
{
    free(Head);
    free(Current);
}

Node* create(int a, int *counter)
{
    Node* ptr=malloc(sizeof(Node));
    if(!ptr)
    {
        printf("ERROR-NOT ENOUGH MEMORY\n");
        free(ptr);
        return 0;
    }
        ptr->data=a;
        ptr->key=*counter;
        counter++;

        return ptr; 

}

void insert(int a, int *counter)
{
    Node* ptr=malloc(sizeof(Node));
    if(!ptr) {
        printf("ERROR-NOT ENOUGH MEMORY\n");
        free(ptr);
    }
    ptr->data=a;
    ptr->key=*counter;

    //point next field to old head
    ptr->next=Head;

    //assign current node as head of singly linked list
    Head=ptr;
    counter++;
}

//Thank you guys over at tutorialspoint for this neat idea for testing this.
//https://www.tutorialspoint.com/data_structures_algorithms/linked_list_program_in_c.htm
void printlist()
{
    Node* ptr=Head;
    printf("TESTING\n");
    while(ptr != NULL) {
        printf("%p*NODE* KEY:%i VALUE:%i PTR NEXT:%p\n \n", ptr, ptr->key, ptr->data, ptr->next);
        ptr=ptr->next;
    }
}

这是我的valgrind输出:

enter image description here

仍在学习很多valgrind输出对我来说非常晦涩难懂而且堆栈交换中的线程关于&#34;信号11(SIGSEGV)&#34;错误也难以理解。

此外,我的代码的任何提示或建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的代码存在问题。请参阅以下行:

int main()
{
    int *keycounter =(int*)malloc(sizeof(int));
    int value = 20;
    keycounter = 0; ===> You are setting the pointer to NULL effectively nullifying the effect of your malloc call above

因此,在您的create函数中,当您尝试访问计数器时,它会导致NULL指针取消引用

Node* create(int a, int *counter)
{
    Node* ptr=malloc(sizeof(Node));
    if(!ptr)
    {
        printf("ERROR-NOT ENOUGH MEMORY\n");
        free(ptr);
        return 0;
    }
        ptr->data=a;
        ptr->key=*counter; ==> Here it will lead to NULL pointer dereference

如果struct中的key成员只是一个整数,那么不需要传递指针(counter是指针),你也可以传递一个整数并设置它。