Added security check to file reading (memory allocations)

This commit is contained in:
Ray 2023-05-22 16:08:14 +02:00
parent 2937f2010c
commit bf69b38056

View file

@ -207,6 +207,8 @@ unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead)
{
data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char));
if (data != NULL)
{
// NOTE: fread() returns number of read elements instead of bytes, so we read [1 byte, size elements]
unsigned int count = (unsigned int)fread(data, sizeof(unsigned char), size, file);
*bytesRead = count;
@ -214,6 +216,8 @@ unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead)
if (count != size) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially loaded", fileName);
else TRACELOG(LOG_INFO, "FILEIO: [%s] File loaded successfully", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to allocated memory for file reading", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read file", fileName);
fclose(file);
@ -344,6 +348,9 @@ char *LoadFileText(const char *fileName)
if (size > 0)
{
text = (char *)RL_MALLOC((size + 1)*sizeof(char));
if (text != NULL)
{
unsigned int count = (unsigned int)fread(text, sizeof(char), size, file);
// WARNING: \r\n is converted to \n on reading, so,
@ -355,6 +362,8 @@ char *LoadFileText(const char *fileName)
TRACELOG(LOG_INFO, "FILEIO: [%s] Text file loaded successfully", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to allocated memory for file reading", fileName);
}
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read text file", fileName);
fclose(file);