1

I recently posted a question about this, but this is a different question. I created a 2D arrays using dynamic memory allocation, after the matrix is used, we need to free the memory by delete it and I dont understand why we cant just use delete [] matrix to delete it instead of the method in the codes below

int **matrix;

    // dynamically allocate an array
    matrix = new int *[row]; 
    for (int count = 0; count < row; count++)
        matrix[count] = new int[col];

    // free dynamically allocated memory
    for( int i = 0 ; i < *row ; i++ )
    {
        delete [] matrix[i] ;
        delete [] matrix ;
    }

Because the problem is because in main() i created a 2D array and assign the values using other int ** functions, i dont know how to delete the allocated memory, the loop will cause runtime error

    int main()
    {
        int **matrixA = 0, **matrixB = 0, **matrixResult = 0; // dynamically allocate an array
        int rowA, colA, rowB, colB; // to hold the sizes of the matrices

        // get values for input method
        int inputMethod = userChoiceOfInput();
        if (inputMethod == 1) // select input by keyboard
        {
            cout << "Matrix A inputting...\n";
            matrixA = getMatricesByKeyboard(&rowA, &colA);
            cout << "Matrix B inputting...\n";
            matrixB = getMatricesByKeyboard(&rowB, &colB);
        }
        else if (inputMethod == 2) // select input by files
        {
            matrixA = getMatricesByFileInput("F:\\matrixA.txt", &rowA, &colA); 
            matrixB = getMatricesByFileInput("F:\\matrixB.txt", &rowB, &colB); 
        }

        //addition(matrixA, &rowA, &colA, matrixB, &rowB, &colB);

        cout << matrixA[1][0];  

////////////////////////run time error///////////////////////
    // free allocated memory of matrix A
    for( int i = 0 ; i < rowA ; i++ )
    {
        delete [] matrixA[i] ;
        delete [] matrixA ;
    }
    // free allocated memory of matrix B
    for( int i = 0 ; i < rowB ; i++ )
    {
        delete [] matrixB[i] ;
        delete [] matrixB ;
    }
////////////////////////run time error///////////////////////

        // free allocated memory of matrix A
        delete [] matrixA ; // i dont know what would these delete
        delete [] matrixB ; 

        return 0;
    }
Casper
  • 1,663
  • 7
  • 35
  • 62

3 Answers3

14

You have to go through your matrix and delete each array. At the end of doing that you can delete the matrix itself

// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
    delete[] matrix[i]; // delete array within matrix
}
// delete actual matrix
delete[] matrix;
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
4

If you are using dynamic arrays anyway I would highly suggest using std::vector. The performance penalty is next to nothing and considering you can use std algorithms more gracefully with vectors your code may very well end up more performant.

unsigned int cols=40, rows=35;
std::vector<int> temp(cols,0); //this is only created so that we can initialize a 
                               //row at a time, the first parameter is the amount of 
                               //elements to initialize with and the second is the value
                               //to initialize with
std::vector<std::vector<int>> matrix(rows,temp); //creates a vector with 35 vectors each
                                                 //initialized with the values in temp

matrix[2][3] = 4;              //use just like a normal array
matrix.resize(88,temp);         //you can add rows later too
matrix.push_back(temp);         //or like this

//probably the most important, you don't need to delete because you never needed to 
//use new in the first place

using new and delete is not really modern style, for good reason. According to the gurus at the C++ and Beyond convention it should be used only in the case of performance optimization and when writing library code. Many books and teachers still teach this way, but on the other hand most books are junk. Here are the gems among them: The Definitive C++ Book Guide and List

Community
  • 1
  • 1
odinthenerd
  • 5,422
  • 1
  • 32
  • 61
  • I agree, they should teach students the basic materials by using modern style not with old stuffs like this!!! – Casper Feb 12 '13 at 10:15
0

Because type int* has no desctructor, at least it has no destructor that you want. You could avoid all memory allocating / deallocation stuff by doing something like this

std::vector<int*> matrix(rows);
std::vector<int> allData(rows * cols);
for(int i = 0; i < rows; i++)
{
matrix[i] = &allData[i * cols];
}

or by using a standard container like boost::numeric::ublas::matrix.