delete array of pointer

Fethullah SİPAHİOĞLU 1 Reputation point
2021-08-19T10:07:57.407+00:00

Hi,

Can one of you ( pls only experts) explain which one is true first or second? Because we know that in the background processer, there is no 2D, 3D, 4D... dimension for the memory. That is after we want to create one 2D or 3D dimensional array, it is allocated 1D consecutively array in the memory. Pls, do not say you have to deallocate for each element of the array. Can you explain why the first terms are wrong as core (including memory)? Because we do not get any error for the first terms on the compiler. Pls, proof. Thx.

First:

int main()
{
    int **container = new int*[n];
    for(int i = 0; i < n; ++i)
        container[i] = new int[size];

    // ... and to deallocate...
    delete [] container;
}

Second:
int main()
{
int **container = new int*[n];
for(int i = 0; i < n; ++i)
container[i] = new int[size];

    // ... and to deallocate...
    for(int i = 0; i < n; ++i)
        delete [] container[i];

    delete [] container;
}
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,559 questions
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 40,941 Reputation points
    2021-08-19T10:35:51.96+00:00

    The first example results in a memory leak -

    Try this to see the leak in a debug build -

    #ifdef _DEBUG  
    #define _CRTDBG_MAP_ALLOC  
    #include <stdlib.h>  
    #include <crtdbg.h>  
    #define _ATL_DISABLE_NOTHROW_NEW  
    #ifndef DBG_NEW  
    #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )  
    //#define new DBG_NEW  
    #endif  
    #else  
    #include <stdlib.h>  
    #endif  // _DEBUG  
      
      
    int main()  
    {  
        constexpr int size{ 50 }, n{ 10 };  
        _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);  
      
        int** container = DBG_NEW int* [n];  
        for (int i = 0; i < n; ++i)  
            container[i] = DBG_NEW int[size];  
      
        // ... and to deallocate...  
      
        // Uncomment to fix memory leak  
        //   
        //for (int i = 0; i < n; ++i)  
        //    delete[] container[i];  
      
        delete[] container;  
    }  
      
    

    Output pane leak report after program terminates -

    124648-leak.png