1

I have some simple code that is generating a warning for seemingly no reason:

// Get the length of the file, with overflow protection
size_t FileLength = GetFileLength(InputFile);
if (FileLength + 1 == 0) return 0;

// Allocate memory and format it as a string
char* FileContents = (char*)malloc(FileLength + 1);
if (FileContents == 0) return 0;
FileContents[FileLength] = 0;
size_t ContentsCursor = 0;

// Copy characters one by one until the measured length is reached
char Character;
while (ContentsCursor != FileLength) {
    Character = fgetc(InputFile);
    FileContents[ContentsCursor] = Character;
    ContentsCursor++;
}

I see no problem with this code, I even added some overflow protection at the top. However, I get this code analysis warning:

Severity    Code    Description Project Path    File    Line    Suppression State
Warning C6386   Buffer overrun while writing to 'FileContents':  the writable size is 'FileLength+1' bytes, but '2' bytes might be written. RanDat  D:\OtherStuff\Programs\C - C++\RanDat   D:\OtherStuff\Programs\C - C++\RanDat\FileFunctions.h   82  

Edit: Forgot to add, I see no case in which the allocation length is less than 2 where it would write 2 bytes. After all, it only writes up to "FileLength", which is always one less than the length of the allocation.

  • There are many dozens of posts on Stack Overflow about this MSVC warning: https://stackoverflow.com/search?q=C6386 – Adrian Mole Jan 16 '23 at 10:27
  • Steam Ranger, Why "Copy characters one by one until the measured length is reached" instead of `fread()`? "I see no problem with this code" --> yet code never checks for errors from `fgetc(InputFile)`. – chux - Reinstate Monica Jan 16 '23 at 10:37
  • Casting the result of malloc on MSVC might be problematic, since it's still some manner of C90 compiler. I wouldn't trust it to give correct diagnostics in case of a missing `#include `. – Lundin Jan 16 '23 at 11:01
  • @chux-ReinstateMonica Errors with `fgetc()` would never cause this problem. At most they'd result in a string full of garbage, but it would still be a valid string. Also, good idea I'd forgotten about `fread()`, thanks! – Steam Ranger Jan 16 '23 at 22:05
  • In trying to solve this mystery, simply trying to remove other deficiencies. Tip: for future issues best to post a [mcve]. – chux - Reinstate Monica Jan 16 '23 at 22:32

0 Answers0