这是我昨天发布的一个问题的延续,我认为这个问题已经解决了,但结果表明我在迭代循环及其退出条件时遇到了另一个问题。我觉得一个新的问题主题可能更合适。
以下freeAllListMembers()函数似乎正在工作,直到循环的最后一次迭代,因为它试图释放“temp”但temp已经被释放,我可以使用什么方法退出此循环并保留它再次跑步,我尝试的一切似乎都没有起作用。
感谢任何见解
int main() {
struct node *head = NULL;
createList(&head);
//do stuff with list
freeAllListMembers(&head);
return 0;
}
int createList(struct node **head) {
struct node *newNode= NULL;
for(int I = 0; I < 100; I++)
{
struct node *node = (struct node*)malloc(sizeof(struct node));
node->data = someData;
node->next = NULL;
//if we havent created an initial start node, create it
if (*head == NULL)
{
*head = node;
}
//otherwise, navigate to the end of the list to add a new node
else
{
newNode = *head;
while (newNode->next != NULL){
newNode = newNode->next;
}
newNode->next = node;
}
}
return 0;
}
void freeAllListMembers(struct node **head){
struct node *temp;
while (*head != NULL) {
temp = *head;
*head = (*head)->next;
free(temp);
}
return;
}
答案 0 :(得分:0)
清理给出的示例以删除一些小的人为错误,程序编译好,我可以在GDB中单步执行。它基本上在编译后没有错误地运行
#include <malloc.h>
#define someData 12345
struct node
{
int data;
struct node* next;
};
int createList(struct node **head )
{
struct node *newNode= NULL;
int i;
for( i = 0; i < 100; i++)
{
struct node *node = (struct node*)malloc(sizeof(struct node));
node->data = someData;
node->next = NULL;
//if we havent created an initial start node, create it
if (*head == NULL)
{
*head = node;
}
//otherwise, navigate to the end of the list to add a new node
else
{
newNode = *head;
while (newNode->next != NULL){
newNode = newNode->next;
}
newNode->next = node;
}
}
return 0;
}
void freeAllListMembers(struct node **head)
{
struct node *temp;
while (*head != NULL) {
temp = *head;
*head = (*head)->next;
free(temp);
}
return;
}
int main()
{
struct node *head = NULL;
createList(&head);
//do stuff with list
freeAllListMembers(&head);
return 0;
}
我只能猜测你在“抽象”中丢失了你的错误。过程