我是一個學習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'中的局部變量,並在函數的開始處對其進行初始化。除非完全有必要,否則請勿使用全局變量。 –