c - Can I use free() formally in VS2013? -
#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 rating (0 - 10):"); scanf("%d", ¤t->rating); while (getchar() != '\n') continue; puts("enter next movie title(empty line stop):"); prev = current; } if (head == null) printf("no data entered."); else printf("here 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; }
why can't code used formally in vs 2013? because of use of free()
function code above can't work? perhaps free()
can't work formally in vs2013???
sorry posting whole code, system said can't submit question due lack of details....
you accessing pointer current
after free
ing it, undefined behaviour. change
while (current != null) { free(current); printf("hehe.\n"); current = current->next; }
to
while (current != null) { struct film *tmp = current; printf("hehe.\n"); current = current->next; free(tmp); }
note shouldn't use gets
@ has been removed recent c standard c11 , notoriously bad it's buffer overrun problems. use fgets() instead.
also, don't cast result of malloc family functions.
Comments
Post a Comment