Can I use free() formally in VS2013?

50 views Asked by At
#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;
}    

Why can't this code be used formally in VS 2013? Is it just because of the use of the free() function that the code above can't work? Perhaps free() can't work formally in VS2013???

Sorry for posting the whole code, but system said that I can't submit this question due to lack of details....

1

There are 1 answers

0
P.P On

You are accessing the pointer current after freeing it, which is 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 that you shouldn't use gets at all as it has been removed from the recent C standard C11 and notoriously bad for it's buffer overrun problems. Use fgets() instead.

Also, don't cast the result of malloc family functions.