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.