Search code examples
c++debuggingsegmentation-faultclion

Program received Segmentation fault while debug in CLion


I have the challenge to implement simplex-method (or simplex algorithm). Simplex-method is a popular algorithm for linear programming which is based on rebuilding matrices. My program should return an optimal solution. I have a C++ project in Clion. It works correctly when I run the program, but during the debug I get a SIGSEGV Signal (Segmentation Fault) in one of the methods. It happens when I try to allocate memory for the matrix. Here is the part of code:

double **newTable;
    newTable = new double *[rows];
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            newTable[i] = new double [cols];
        }
    }

I free the memory at the end of the method using delete[], but it doesn’t work. I’ve already tried to run the program in another IDE (CodeBlocks), but it works properly too, and I have no idea why it happens and where the problem occurs.


Solution

  • No need for this nested loop. You only need one loop to allocate memory for this jagged array:

    int main() {
        int rows = 5, cols = 10;
        double **newTable;
        newTable = new double *[rows];
        for (int i = 0; i < rows; ++i) 
            newTable[i] = new double[cols];
    
        for (int i = 0; i < rows; ++i)
            delete newTable[i];
        delete newTable;
    }
    

    The way your code is now it will leak memory, but that alone won't cause a segmentation fault. There might be a mistake with how you're freeing the memory, too.


    Also, since this is C++, may I recommend using std::vector instead?

    #include <vector>
    int main() {
        std::vector<std::vector<double>> newTable(5, std::vector<double>(10));
    }