这是我的完整程序:
#include <stdio.h>
#include <stdlib.h>
#define kArraySize 50
#define kFirstElement 0
struct Name {
char name[kArraySize + 1];
struct Name *nextName;
} *gFirstNameNode, *gLastNameNode;
char GetName(struct Name *currentName);
void AddToList(struct Name *currentName);
void PrintList(struct Name *gFirst);
void FreeTheMemory(struct Name *gFirst);
int main(void) {
struct Name *currentName;
char character;
int counter;
gFirstNameNode = NULL;
gLastNameNode = NULL;
do {
currentName = malloc(sizeof(struct Name));
if (currentName == NULL) {
printf("Out of Memory!\n");
exit(0);
} else {
for (counter = 0; counter <= kArraySize; counter++)
currentName->name[counter] = '\0';
}
character = GetName(currentName);
if ((currentName->name[kFirstElement]) != '\0') {
AddToList(currentName);
}
} while (character != '\r');
PrintList(gFirstNameNode);
printf("Freeing list memory");
FreeTheMemory(gFirstNameNode);
printf("\nFreeing Current Memory!\n");
free(currentName);
printf("Program Ended");
return 0;
}
char GetName(struct Name *currentName) {
char c;
int counter = 0;
printf("Enter a name (hit 'return' to exit):");
for (counter = 0; (counter <= kArraySize) && ((c = getchar()) != '\n'); counter++) {
currentName->name[counter] = c;
}
if (counter == 0) {
return '\r';
} else {
currentName->name[counter + 1] = '\0';
return '\0';
}
}
void AddToList(struct Name *currentName) {
if (gFirstNameNode == NULL) {
gFirstNameNode = currentName;
} else {
gLastNameNode->nextName = currentName;
}
gLastNameNode = currentName;
currentName->nextName = NULL;
}
void PrintList(struct Name *gFirst) {
struct Name *currentPointer;
if (gFirstNameNode == NULL) {
printf("No names in list\n");
printf("----------------\n");
} else {
for (currentPointer = gFirst; currentPointer != NULL; currentPointer = currentPointer->nextName) {
printf("Name: %s\n", currentPointer->name);
}
}
}
void FreeTheMemory(struct Name *gFirst) {
struct Name *currentPointer;
for (currentPointer = gFirst; currentPointer != NULL; currentPointer = currentPointer->nextName) {
free(currentPointer);
printf(".");
}
}
这就是我不确定自己所做的是否正确的地方。我在自学,所以请容忍我。我要做的是从第一个节点到最后一个节点删除链表的节点。为此,我创建了以下函数。:
void FreeTheMemory(struct Name *gFirst) {
struct Name *currentPointer;
for (currentPointer = gFirst; currentPointer != NULL; currentPointer = currentPointer->nextName) {
free(currentPointer);
printf(".");
}
}
我不确定释放currentPointer是否真的释放了链表。换句话说,我想知道我的逻辑是否正确。我没有人可以问,所以我非常感谢你的帮助。
最佳答案
你这样做有问题:
free(currentPointer);
接下来是:
currentPointer = currentPointer->nextName
在释放下一个名称之后,您不能遵从
currentPointer
来获取下一个名称。相反,你应该这样做:
currentPointer = gFirst;
while ( currentPointer ) {
struct Name * next = currentPointer->nextName;
free(currentPointer);
currentPointer = next;
}
关于c - 在单链列表中使用“for”循环的free()内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35977719/