user1251096
user1251096

Reputation:

Program crashes with fclose

I am working with the following text file: https://mega.nz/#!EN4iRJxA!VtKFEl9dlQHWHIzcgfOfpXTt9_ill_YkgsLWL3nORLg And the following code:

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct
    {
        int id;
        char lastname[25];
        char name[20];
        float average;
    }student;

    int main(){
        int i;
        student *pointer= (student*) malloc(3);

        FILE *file= fopen("Struct.txt", "r");
        fread(pointer, sizeof(student), 3, file);
        for(i= 0; i< 3; i++){
            printf("Id: %d\nName: %s\nLast name: %s\nAverage: %.2f\n",
                (pointer+ i) -> id,
                (pointer+ i) -> name,
                (pointer+ i) -> lastname,
                (pointer+ i) -> average);
        }
        fclose(file);
        system("pause");
        return 0;   
    }

When I delete the fclose function it works but I checked it and seems to be correct. What am I missing?

Upvotes: 1

Views: 2435

Answers (2)

tdao
tdao

Reputation: 17713

It has nothing to do with your fclose, instead you need to fix two things:

  • You need to check the return error of fopen:

    if( NULL == file )
    {
        printf( "Cannot open\n" );
        exit( 1 );
    }
    
  • Your malloc code doesn't look right, should be: student *pointer= malloc(3 * sizeof(student));

Upvotes: 5

Will Angley
Will Angley

Reputation: 1394

Your program isn't allocating memory the way you think it is. malloc(3) returns three bytes of memory. Most likely the file pointer is immediately after it in memory

[ | | ][*FILE]

When you read in the file, the data first goes in to the three bytes of memory you've allocated. But since it doesn't fit, it keeps going and overwrites the memory containing the pointer to the file too.

[student data student data]

Then calling fclose closes the file at dat or whatever was read in from the file. This is a programming error, sometimes called a "wild pointer dereference", and if the data read in doesn't point to something that can be closed like a file can (as is happening to you) the program will crash.

The fixes suggested by artm should resolve your problem, but I thought this explanation might help you understand why you saw the crash.

Upvotes: 3

Related Questions