Gaurav Gaurav - 1 month ago 14
C Question

fread leads to heap overflow

Using below c code snippet

char charString[1024];

if (fread(charString, sizeof_data, 1, filePointer) != 1){ return false;}
else return true;


If I provide
sizeof_data = 1024 and file pointed by filePointer have only 10bytes to read from file. I receive Abort signal from program.

How do I handle it gracefully?

Answer

What you say can't be true: sizeof_data is 1024 and the buffer is too, so no problem there. So the problem is in code you don't show us. Two possibilities:

  1. sizeof_data is larger than the buffer and you overwrite the stack (or other data);

  2. You expect to read a string and don't terminate it with `\0' and later you print it, causing f/s/printf to cause a segfault.

Try this code:

    char charString[1024];
    size_t n;

    if ((n=fread(charString, 1, (sizeof_data<1024?sizeof_data:1023), filePointer))==0)
        return false;
    CharString[n]='\0';          // terminate
    printf("%s\n",charString);   // safe to print now
    return true;

Note that we want to read chars, so item size is 1, and we want to read up to 1023 of them, so count is max 1024.

Comments