Search code examples
c++visual-studiomatrixaccess-violationdynamic-allocation

Access violation reading location on dynamic allocated matrix


I have a problem with a dynamically allocated matrix. I get this error: "Exception thrown at 0x009087AC in Tema 1.exe: 0xC0000005: Access violation reading location 0xFDFDFDFD." What I'm trying to do is delete a line from a matrix:

void deleteLine(int **matrix, int &nrLin, int nrCol, int lineDel)
{
    for (int indexLin = lineDel; indexLin < nrLin; indexLin++)
        for (int indexCol = 0; indexCol < nrCol; indexCol++)
            matrix[indexLin][indexCol] = matrix[indexLin + 1][indexCol];
    nrLin--;
}
int main()
{
    int **matrix, nrLines, nrColumns, lineDel;
    ifstream file("datePB4.txt");
    file >> nrLines>> nrColumns;
    matrix= new int *[nrLines];
    for (int index = 0; index < nrLines; index++)
        matrix[index] = new int[nrColumns];
    for (int indexLin = 0; indexLin < nrLines; indexLin++)
        for (int indexCol = 0; indexCol < nrColumns; indexCol++)
            file >> matrix[indexLin][indexCol];
    cin >> lineDel;
    deleteLine(matrix, nrLines, nrColumns, lineDel);
    for (int index = 0; index < nrLines; index++)
        delete matrix[index];
    delete matrix;
    file.close();
    return 0;
}

I get the error in the 5th line ("matrix[indexLin][indexCol] = matrix[indexLin + 1][indexCol];").

Any help would be appreciated, thanks!


Solution

  • You are reading outbound of the array:

    matrix[indexLin][indexCol] = matrix[indexLin + 1][indexCol];
    

    So the last iteration indexLin is equal to nrLin -1 which is OK but in matrix[indexLin + 1][indexCol]; you read matrix[indexLin(-1 + 1)] which is not an elelement of the array which causes the program carsh.

    You can modify it to:

    for (int indexLin = lineDel; indexLin < nrLin - 1; indexLin++) // here solves the problem in order not to read matrix[indexLen]
        for (int indexCol = 0; indexCol < nrCol; indexCol++)
            matrix[indexLin][indexCol] = matrix[indexLin + 1][indexCol];