gpt4 book ai didi

我可以在VS2013中正式使用free()吗?

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

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TSIZE 45
struct film{
char title[TSIZE];
int rating;
struct film *next;
};

int main(void)
{
struct film *head = NULL;
struct film *prev, *current;
char input[TSIZE];

puts("Enter first movie title:");
while (gets(input) != NULL && input[0] != '\0')
{
current = (struct film*)malloc(sizeof(struct film));
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy(current->title, input);
puts("Enter your rating (0 - 10):");
scanf("%d", &current->rating);
while (getchar() != '\n')
continue;
puts("Enter next movie title(empty line to stop):");
prev = current;

}

if (head == NULL)
printf("No data entered.");
else
printf("Here is the movie list:\n");
current = head;
while (current != NULL)
{
printf("Movie: %s Rating: %d\n", current->title, current->rating);
current = current->next;
}
current = head;
while (current != NULL)
{
free(current);
printf("hehe.\n");
current = current->next;
}
printf("Bye!\n");

return 0;
}

为什么这段代码不能在VS 2013中正式使用?难道只是因为使用了free()函数,上面的代码就无法工作了吗?也许free()无法在VS2013中正式工作???

很抱歉发布整个代码,但系统说由于缺乏详细信息,我无法提交此问题......

最佳答案

您在释放之后访问指针current,这是未定义的行为。改变

while (current != NULL)
{
free(current);
printf("hehe.\n");
current = current->next;
}

while (current != NULL)
{
struct film *tmp = current;
printf("hehe.\n");
current = current->next;
free(tmp);
}

请注意,您根本不应该使用 gets,因为它已从最近的 C 标准 C11 中删除,并且因其缓冲区溢出问题而臭名昭著。使用fgets()相反。

另外,不要强制转换 malloc family functions 的结果.

关于我可以在VS2013中正式使用free()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647364/

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