Why does fclose() fail?
<p>Please look at the following code: </p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;sys/stat.h&gt;


void main() {

    struct stat file_st;
    int size=0, ret=0;
    char* buf=NULL;
    FILE* file = fopen("newfile", "r");
    if (file==NULL) {
        printf("error");
        exit(1);
    }

    if (stat("newfile", &amp;file_st)!=0) {
        printf("stat failed\n");
        exit(1);
    }
    buf = (char*)malloc(sizeof(file_st.st_size+1));
    buf[file_st.st_size]='\0';
    ret = fread(buf, 1, file_st.st_size, file);
    printf("fread return value is: %d\n");
    ret = fclose(file);
    printf("fclose return value: %d\n", ret);
    printf("%s\n", buf);

}
</code></pre>

<p>This code passes compilation, but crashes while running. Do you know why? </p>

<p>However, if I switch between the fclose() and printf() (the last two lines of the code), then the code runs successfully and prints the content of "newfile". What is the difference between these two cases? </p>