首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用链表分割故障(信号11西格赛克)

用链表分割故障(信号11西格赛克)
EN

Stack Overflow用户
提问于 2016-11-29 05:11:21
回答 1查看 223关注 0票数 0

写了一个程序,在pset5之前用链表和指针练习,留下两个内存错误,我一直无法弥补。

代码语言:javascript
复制
#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;
    }
}

这是我的英勇输出:

但是,对我来说,学习大量的英勇输出还是很难理解的,关于"signal 11 (SIGSEGV)“错误的堆栈交换线程也很难理解。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-29 05:43:22

您的代码中有一个问题。见以下几行:

代码语言:javascript
复制
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

因此,在创建函数中,当您尝试访问计数器时,它将导致空指针取消引用。

代码语言:javascript
复制
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成员只是一个整数,那么就不需要传递指针(计数器是一个指针),您还可以传递一个整数并设置它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40858250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档