MouseToVJoy
MouseToVJoy copied to clipboard
Segmentation fault on FileRead class
The function "newFile" in the FileRead class is accessing a position outside of the "checkArray" length, which may result in accessing a protected memory region (Segmentation fault).
The issue is the maximum value of 'i' is 32 but the checkArray in that case is 23:
// Segmentation fault
for(int i = 0; i < 32; i++){
if (tmp == checkArray[i]) {
_resultArray[i] = value;
}
}
I think a simple fix can be like this:
// fileread.h
// { ... } Others includes
#include<vector>
class FileRead {
public:
BOOL newFile(std::string fileName, std::string checkArray[], size_t checkArraySize);
double result(int number) {
if (_resultArray && number < _resultLen)
return _resultArray[number];
else
{
// Some error handling
}
};
private:
size_t _resultLen = 0;
double* _resultArray = NULL;
};
Each time you call the 'newFile' function, it will free the old memory if it exists and allocates a new one to store the results.
// fileread.cpp
BOOL FileRead::newFile(std::string fileName, std::string checkArray[], size_t checkArraySize) {
if (this->_resultArray)
free(_resultArray); // Free de old allocated memory
this->_resultLen = Lenght;
if(!(_resultArray = static_cast<double*>(malloc(sizeof(double) * Lenght)))) // Allocate a new memory ( can be done with 'new(double[size])' )
return FALSE;
ZeroMemory(_resultArray, Lenght * sizeof(double));
std::ifstream file(fileName);
if (!file.is_open())
{
printf("Config file not found\n");
return FALSE;
}
// { ... } Code
for(int i = 0; i < checkArraySize; i++){
if (tmp == checkArray[i]) {
_resultArray[i] = value;
}
}
// { ... } Code
file.close();
return TRUE;
}