分段错误(葛11 SIGSEGV)用链表
问题描述:
在写程序pset5之前链表和三分球练习前,留下了,我一直无法弥补两个内存错误我。分段错误(葛11 SIGSEGV)用链表
#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的输出是相当神秘,我和有关堆栈交换线程“信号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
因此,在您创建功能,当您尝试访问计数器,它是导致空指针引用
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
成员的结构只是一个整数,那么不需要传递一个指针(计数器是一个指针),你也可以传递一个整数并设置它。
+2
比这还糟糕。设置一个指向地址'0'的指针就在*系统保留的内存范围*内,并且试图访问或写入它将保证段错误。 –
你必须正确处理好'next'成员。创建节点时始终用NULL初始化,并在节点添加到列表时适当更改。 – GMichael
一个好的开始是附加一个诸如'gdb'的调试器,然后查看堆栈跟踪以了解程序崩溃的位置。 – paddy
在此发布您的代码而不是发布链接。 – 4386427