You are here:

C++/truble with dynamic memory allocation

Advertisement


Question
How can I delete 2D array of pointers while using dynamic allocation of memory?

Answer
Question:
----------
Subject: truble with dynamic memory allocation

How can I delete 2D array of pointers while using dynamic allocation of memory?

Answer:
-------


You give little detail on exactly how you are allocating and using this 2D array of pointers.

I am assuming you are using C++ (in fact a hosted implementation of ISO standard C++) not C, hence you use the new [] and delete [] operators and not the C malloc and free library functions.

You cannot dynamically create anything other than 1D arrays (i.e. vectors) of objects in C++ (and of course single objects).

However, due to the fact that in C and C++ multidimensional built in array types are composed of vectors of arrays which may themselves be vectors, or vectors of vectors etc. you can create dynamically a vector of vectors-of-fixed-size. That is only _one_ dimension can be  determined dynamically at runtime.

So do you mean you have an effective 2D array by having a vector (1D array) containing pointers to further vectors of objects?

Or do you mean you have a 2D array in which one dimension is fixed at compile time (that is, static) and the other is determined at runtime (i.e. dynamic), and the contents of this 2D array are pointer to other objects?

Or some other arrangement?

I shall assume the first possibility for the purposes of illustration: you are using a dynamically created vector of pointers which point to further dynamically created vectors.

So to create an effective 2D array using a vector of pointers to vectors you first create the vector of pointers, then you create vectors for each element in the vector of pointers (note that in C and C++ creating a pointer does not mean it points to anything in particular - in most allocation scenarios it is not even initialised to a known value by default):

   int ** CreateSurfaceOfInts( std::size_t x_dimension, std::size_t y_dimension )
   {
       int ** surface = new int*[x_dimension];
       
       for (std::size_t i=0; i < x_dimension; ++i )
       {
         surface[i] = new int[y_dimension];
       }
       
       return surface;
   }

[Apologies if the indentation looks odd for any for the posted code - it was written using fixed space font and spaces not tabs and does not always translate to being displayed well on AllExperts]

You then have to destroy the objects in a similar fashion but the reverse order, that is delete the vectors or objects pointed to by the elements of the vector of pointers and then delete the vector of pointers. Note that this implies we need to know the dimensional size of the vector of pointers:

   void DestroySurfaceOfInts( int ** surface, std::size_t x_dimension )
   {
       for (std::size_t i=0; i < x_dimension; ++i )
       {
         delete [] surface[i];
       }
       delete [] surface;          
   }

I use the term Surface as a surface has 2 dimensions, whereas an object (in the geometric or graphics sense) has 3 dimensions. I show the procedures as functions although you need not do so. We could use the functions like so:

   int main()
   {
       std::size_t const XDim(7);
       std::size_t const YDim(13);

       auto surface = CreateSurfaceOfInts(XDim,YDim);

       for ( std::size_t x=0; x<XDim; ++x )
       {
         for ( std::size_t y=0; y<YDim; ++y )
         {
         surface[x][y] = static_cast<int>(x)*100 + static_cast<int>(y);
         }
       }

       for ( std::size_t x=0; x<XDim; ++x )
       {
         for ( std::size_t y=0; y<YDim; ++y )
         {
         std::cout << "surface["<<x<<"]["<<y<<"] = "<<surface[x][y]<<"\n";
         }
       }

       DestroySurfaceOfInts(surface, XDim);
   }

[std::size_t requires header cstdlib to be included and std::cout requires header iostream to be included

   #include <cstdlib>
   #include <iostream>
]

The use of auto in main:

       auto surface = CreateSurfaceOfInts(XDim,YDim);

is a new C++11 feature that says to the compiler "the type of this variable is whatever you think the result type of the expression used to initialise it is" - in this case surface will be int ** - the type returned from CreateSurfaceOfInts. If your compiler does not support this feature just replace auto with int** .

Now the above is true if the vector of pointers _owns_ the things its elements point at. If it does not then we can just use the array delete operator (operator delete []) :

   delete [] surface;

As surface in this case does not own the things its elements point to it is not responsible for deleting them.

You can modify / extend the basic notions here to cover other similar scenarios.

For more in depth treatment of this topic and background material please refer to this previous answer of mine:

   http://en.allexperts.com/q/C-1040/2008/4/deleting-multidimensional-array-pointer

[note: the bit about possible padding between array elements is wrong - array elements have no padding between them (however an element may itself contain unused padding storage if the elements are of class/struct/union type, and such space adds to the size of objects of the type)]

Hope this helps.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.