Hi,am newbie to c programming.can u explain the above c program which reads a file more than its capcity..
i couldn understand more than this..

Thanks,Yasokrish.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int bof(FILE *badfile)
{
    char buffer[12];
    
    fread(buffer, sizeof(char), 40, badfile);
    return 1;
}
int main(int argc, char **argv)
{
    FILE *badfile;
    badfile = fopen("badfile", "r");
    bof(badfile);
    printf("Returned Properly\n");
    fclose(badfile);
    return 1;
}

fread statement reads the first 40 bytes from a file and puts them in a character array called buffer.

buffer is only 12 bytes in size.

this situation is generally considered to be A Bad Thing.

The above problem is an example of buffer overflow ( stack overflow)
fread tries to store data in a buffer outside the memory the programmer set aside for it (12 bytes)

Also it is a good practice to validate the file pointer after opening the file. You should check badfile after the statement badfile = fopen("badfile", "r");

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.