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

时间:2015-06-04 14:58:48

标签: c visual-studio-2013

Element

为什么不能在VS 2013中正式使用此代码?仅仅是因为使用了#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; } 函数,上面的代码才能起作用吗? 也许free()无法正式在VS2013中工作???

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

1 个答案:

答案 0 :(得分:1)

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

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的结果。