gpt4 book ai didi

c - 有时在 C 中修复段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:17 24 4
gpt4 key购买 nike

我是学c的初学者,分割对我来说发生了很多次。我也在网上做了一些关于段错误的研究:一些原因是分配内存问题、空指针或内存访问问题。但我很困惑,为什么有时代码有效,但有时却说段错误?下面是我在 insertAtdestroyList 函数中遇到这个问题的代码:

#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 下运行您的程序,如下所示:

$ gdb ./a.out
(gdb) run
...
Segmentation fault
(gdb) bt

这将打印回溯,显示代码中导致错误的位置以及调用它的任何函数。如果段错误发生在库函数中,请继续查看回溯,直到找到您的代码,看看您可以在那里修复什么。

关于c - 有时在 C 中修复段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39233426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com