multivac61
multivac61

Reputation: 35

Program hangs if both written to and read from file in same execution

I would expect the following code to write the number 42 to a binary file and then read and print out the exact value. And it does that but then it will not exit, just stall as it would when waiting for user input. Here is code that does what I explained:

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

int main(int argc, char argv[]){

    char *filename = "test.db";
    int *my_int = calloc(1, sizeof(int));
    *my_int = 42;

    // First we open file to write to it
    FILE *file = fopen(filename, "w");
    fwrite(my_int, sizeof(int), 1, file);
    fflush(file);
    free(file);

    // Then we want to read from it
    *my_int = -1;
    file = fopen(filename, "r");
    fread(my_int, sizeof(int), 1, file);
    free(file);

    printf("Read back %d\n", *my_int);

    return 0;
}

I know that I can simply open it with the w+ flag but I am just curious to figure out why it just stalls..

Upvotes: 0

Views: 214

Answers (2)

sjsam
sjsam

Reputation: 21965

Use [ fclose ] to close the file.

fclose(file);

Also, the reference says :

All internal buffers associated with the stream are disassociated from it and flushed:

So

fflush(file);

could be avoided here.

Use [ free ] to release the reserved memory for a pointer. In your case

free(my_int); 

would make sense, if placed before return.

Upvotes: 2

PC Luddite
PC Luddite

Reputation: 6088

You don't free a file pointer, you fclose it. Calling free() on a file opened with fopen is undefined behavior.

I'm sure if you replace your free(file) lines with fclose(file), your problem will be solved.


I also recommend that you not bother allocating memory for my_int with calloc if you're using it only within that function. It may be better to place that memory on the stack, i.e. int my_int instead of int* my_int = calloc(sizeof(int)). The latter requires you to call free() later in the program, whereas the former does not.

Upvotes: 7

Related Questions