我是一个学习c的初学者,并且分割对我来说会发生很多次。我也在网上做了一些关于分段错误的研究:一些原因是分配内存问题,空指针或内存访问问题。但我很困惑,为什么有时代码可以工作,但有时它说分段错误?下面是代码,我在两个insertAt
和destroyList
功能得到这个问题:修复分割错误有时在C
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE{
int data;
struct NODE* next;
} node;
node* insertAt(node*, int, int);
void printList(node*);
void destroyList(node*);
node* myList;
int counter = -1;
int main()
{
myList = NULL;
int pos, input;
myList = insertAt(myList, 0, 333);
myList = insertAt(myList, 0, 555);
myList = insertAt(myList, 1, 222);
myList = insertAt(myList, 3, 444);
printf("My List:\n");
printList(myList);
destroyList(myList);
printf("After Destroy:\n");
printList(myList);
return 0;
}
node* insertAt(node* head, int pos, int newData)
{
node* temp = (node*) malloc(sizeof(node));
temp->data = newData;
counter++;
if(head == NULL){
head = temp;
return head;
}else if (pos == 0)
{
temp->next = head;
head = temp;
return head;
}else if(head != NULL && pos > counter){
node* current = head;
node* temp2 = current;
while(current != NULL){
temp2 = current;
current = current->next;
}
temp->next = current;
temp2->next = temp;
return head;
}else
{
node* current = head;
while(pos-1>0){
current = current->next;
pos--;
}
temp->next = current->next;
current->next = temp;
return head;
}
}
void printList(node* head)
{
node* ptr = head;
while (ptr != NULL) {
printf("%i ", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
void destroyList()
{
node* temp;
while(myList){
temp = myList;
myList = temp->next;
free(temp);
}
}
你有一个很奇怪的分裂全局变量和局部变量... –
尝试使用gdb进行调试 – Dave
全局变量'counter'不会为* next *列表插入重置。将它作为'insertAt'中的局部变量,并在函数的开始处对其进行初始化。除非完全有必要,否则请勿使用全局变量。 –