带链表的分段错误(信号 11 sigsegv)

Segmentation Fault (singal 11 sigsegv) with linked list

在编写 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 输出:

仍在学习,很多 valgrind 输出对我来说非常神秘,关于 "signal 11 (SIGSEGV)" 错误的堆栈交换线程也很难理解。

此外,如果您对我的代码有任何提示或建议,我们将不胜感激。

你的代码有问题。请参阅以下行:

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

因此,在您的创建函数中,当您尝试访问计数器时,它会导致 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

如果你的key成员在struct中只是一个整数,那么就不用传递指针了(counter是指针),你也可以传递一个整数然后设置。