0

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;
}
3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by muditAggarwal
0

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.

0

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");

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.