[cppcheck] Fix errors in core.c

There were errors only in function SaveStorageValue():

* Common realloc mistake: 'fileData' nulled but not freed upon failure
* Memory pointed to by 'fileData' is freed twice.

Validation:
* Tested examples/core/core_storage_values.c
* Launched Unit Test for this function
* Rerun CPPCHECK afer fix
This commit is contained in:
danimartin82 2020-03-26 15:21:28 +01:00
parent 7ae7a87f8a
commit a16cf8c140

View File

@ -2208,30 +2208,52 @@ void SaveStorageValue(int position, int value)
#endif #endif
int dataSize = 0; int dataSize = 0;
int new_dataSize = 0;
unsigned char *fileData = LoadFileData(path, &dataSize); unsigned char *fileData = LoadFileData(path, &dataSize);
unsigned char *new_fileData = NULL;
if (fileData != NULL) if (fileData != NULL)
{ {
if (dataSize <= (position*sizeof(int))) if (dataSize <= (position*sizeof(int)))
{ {
// Increase data size up to position and store value // Increase data size up to position and store value
dataSize = (position + 1)*sizeof(int); new_dataSize = (position + 1)*sizeof(int);
fileData = (unsigned char *)RL_REALLOC(fileData, dataSize); new_fileData = (unsigned char *)RL_REALLOC(fileData, new_dataSize);
int *dataPtr = (int *)fileData;
if (new_fileData != NULL)
{
// RL_REALLOC succeded
int *dataPtr = (int *)new_fileData;
dataPtr[position] = value; dataPtr[position] = value;
} }
else else
{ {
// RL_REALLOC failed
TRACELOG(LOG_INFO, "Position in bytes [%d] bigger than actual size of file [%d] Realloc function FAIL",position*sizeof(int),dataSize);
// We store the old size of the file.
new_fileData=fileData;
new_dataSize=dataSize;
}
}
else
{
// We store the old size of the file.
new_fileData=fileData;
new_dataSize=dataSize;
// Replace value on selected position // Replace value on selected position
int *dataPtr = (int *)fileData; int *dataPtr = (int *)new_fileData;
dataPtr[position] = value; dataPtr[position] = value;
} }
SaveFileData(path, fileData, dataSize); SaveFileData(path, new_fileData, new_dataSize);
RL_FREE(fileData); RL_FREE(new_fileData);
} }
else else
{ {
TRACELOG(LOG_INFO, "Storage file not found, creating a new one.");
dataSize = (position + 1)*sizeof(int); dataSize = (position + 1)*sizeof(int);
fileData = (unsigned char *)RL_MALLOC(dataSize); fileData = (unsigned char *)RL_MALLOC(dataSize);
int *dataPtr = (int *)fileData; int *dataPtr = (int *)fileData;