gpt4 book ai didi

c - 如何释放分配给 C 中指针的内存?

转载 作者:行者123 更新时间:2023-11-30 15:30:09 25 4
gpt4 key购买 nike

我在 C 中有一个函数,可以将一个新问题添加到单链表的头部:

int AddQuestion()
{
unsigned int aCount = 0;
Question* tempQuestion = malloc(sizeof(Question));

tempQuestion->text = malloc(500);

fflush(stdin);
printf("Add a new question.\n");
printf("Please enter the question text below:\n");
fgets(tempQuestion->text, 500, stdin);
printf("\n");
fflush(stdin);
printf("How many answers are there?: ");
scanf("%u", &tempQuestion->numAnswers);
fflush(stdin);
tempQuestion->answers = malloc(sizeof(Answer*) * tempQuestion->numAnswers);
for (aCount = 0; aCount < tempQuestion->numAnswers; aCount++)
{
tempQuestion->answers[aCount] = malloc(sizeof(Answer));
tempQuestion->answers[aCount]->content = malloc(250);
printf("Enter answer #%d: \n", (aCount + 1));
fgets(tempQuestion->answers[aCount]->content, 250, stdin);
fflush(stdin);
printf("Is it correct or wrong? correct = 1, wrong = 0: ");
scanf("%u", &tempQuestion->answers[aCount]->status);
fflush(stdin);
}

tempQuestion->pNext = exam.phead;
exam.phead = tempQuestion;

printf("\n");
fflush(stdin);

return 1;
}

如您所见,我使用 malloc() 来分配新问题所需的空间。但是,如果我尝试对 tempQuestion 调用 free(),则会从考试中删除该问题。我不想删除问题,除非问题被删除或程序终止。

我有一个清理函数,应该 free() 释放所有已用内存,但它不会释放 addQuestion() 函数中的 tempQuestion。

void CleanUp()
{
unsigned int i = 0;
Question* tempQuestion = NULL;

if (exam.phead != NULL) {
while (exam.phead->pNext != NULL) {
tempQuestion = exam.phead;
exam.phead = tempQuestion->pNext;
for (i = 0; i < tempQuestion->numAnswers; i++) {
free(tempQuestion->answers[i]->content);
free(tempQuestion->answers[i]);
}
free(tempQuestion->pNext);
free(tempQuestion->text);
free(tempQuestion);
}
free(exam.phead);
}
}

如何在 addQuestion() 函数中 free() tempQuestion 以便它仅在执行结束时释放内存?我正在使用 Visual Studio C++ 2012,但我必须仅使用 C 语法(无 C++)进行编写。我对 C 编程也相当陌生。谢谢!

最佳答案

回答你的问题:你不知道。您不应在 AddQuestion 函数中调用 free(tempQuestion),因为这会释放您刚刚分配的内存。

当您将一个指针分配给另一个指针时,仅复制该指针,而不是它所指向的内容。

关于c - 如何释放分配给 C 中指针的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25766121/

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