Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Segmentation fault on FileRead class #13

Open
Guila767 opened this issue Oct 6, 2019 · 1 comment
Open

Segmentation fault on FileRead class #13

Guila767 opened this issue Oct 6, 2019 · 1 comment

Comments

@Guila767
Copy link

Guila767 commented Oct 6, 2019

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;
}
@xCuri0
Copy link

xCuri0 commented Aug 26, 2021

Fixed in my fork

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants