【发布时间】:2017-01-07 02:08:00
【问题描述】:
我是学习c的初学者,分割对我来说发生了很多次。我也在网上做了一些关于分段错误的研究:一些原因是分配内存问题、空指针或内存访问问题。但是我很困惑,为什么有时代码可以工作,但有时却说分段错误?以下是我在 insertAt 和 destroyList 函数中遇到此问题的代码:
#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调试
-
全局变量
counter不会为 next 列表插入重置。使其成为insertAt中的局部变量,并在函数开始时对其进行初始化。除非完全必要,否则请不要使用全局变量。 -
在我将
node* head添加到您的destroyList定义中,并用head替换其主体中每次使用myList之前,您的程序不会为我编译。避免使用全局变量。 -
@SuvP 在 c11 模式下使用 clang 3.8 编译,我的工具链也没有发出警告/错误。我希望看到你做了什么,但它不仅编译了,它实际上运行(当然是直接进入 UB)。在源代码底部定义的参数列表中填充
void,最终让编译器呕吐。
标签: c linked-list segmentation-fault