53696

Correct allocate and free memory for arrays in C++

I'm dealing with dynamic arrays. The function empty_matrix() creates a new array, representing a matrix. delete_matrix() frees all memory, allocated for the matrix.

Do I get a memory leak in function example() if I call add(add(a, b), c)? What will happen to the memory allocated in the function add(...)? Do I have to free it? Where should I do it?

matrix empty_matrix(int dim) { matrix m; m.dim = dim; m.data = new int*[dim]; for (int i = 0; i < dim; i++) m.data[i] = new int[dim]; return m; } void delete_matrix(matrix m) { for (int i = 0; i < dim; i++) delete [] m.data[i]; delete [] m.data; } matrix add(matrix a, matrix b) { matrix c = empty_matrix(a.dim); for (int i = 0; i < a.dim; i++) for (int j = 0; j < a.dim; j++) c.data[i][j] = a.data[i][j] + b.data[i][j]; return c; } void example() { matrix a = empty_matrix(100); matrix b = empty_matrix(100); matrix c = empty_matrix(100); // some modifications of a, b and c // ... matrix d = add(add(a, b), c); print_matrix(d); delete_matrix(a); delete_matrix(b); delete_matrix(c); delete_matrix(d); }

Answer1:

What you <strong>should</strong> do is use Object Orientation/RAII. Your data member of matrix class should be private, and memory for it should be allocated in the constructor, and freed in the destructor. This way, you won't have to worry about memory leaks.

For example...

class matrix { public: typedef int element_type; matrix(int dimension) :data_(new element_type[dimension*dimension]) { } //Do define your copy-constructor and assignment operators ~matrix() { delete [] data_; } private: element_type* data_; };

This all, of course, if this is homework. If it is not, then you should refrain from using arrays in this situation. Use std::vectors

Answer2:

Yes, you will have to free the result of any empty_matrix or add call using delete_matrix. You're leaking memory, because you're not freeing the matrix of the innermost add call.

Answer3:

You should have exactly one new for one delete and one new[] for one delete[] in your code. That's the most important principle.

Hence, if the function add creates a new matrix, it needs to be deleted somewhere.

<hr>

Also, empty_matrix should be the constructor of the matrix class, and delete_matrix should be its destuctor.

You could also replace the data with a std::vector and your memory handling would be much more automated, relieving you from the necessity of counting news and deletes.

Recommend

  • MPI - Sending and Receiving a column
  • Add-In Commands Ribbon shows in Excel Online but not in Excel for Windows
  • AWS SES Production Access setup with Meteor
  • jQuery Mobile - Dialogs without changing hash
  • Entity Framework ObjectContext: Concurrency
  • Double-click autofill - dynamic based on adjacent cell
  • Excel VBA URLDownloadToFile Error for https Ressource
  • Creating a Multidimensional, Associative Array in VBScript
  • Conversion from string “a” to type 'Boolean' is not valid
  • Adding a button at the bottom of a table view
  • Can I display google adwords (AdView) in javafx on android
  • Getting last autonumber in access
  • Uncaught Error: Could not find module `ember-load-initializers`
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • output of program is not same as passed argument
  • Javascript + PHP Encryption with pidCrypt
  • Delete MySQLi record without showing the id in the URL
  • GridView Sorting works once only
  • trying to dynamically update Highchart column chart but series undefined
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Getting Messege Twice Using IMvxMessenger
  • embed rChart in Markdown
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • Django query for large number of relationships
  • Sorting a 2D array using the second column C++
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • costura.fody for a dll that references another dll
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Observable and ngFor in Angular 2
  • How can i traverse a binary tree from right to left in java?
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • UserPrincipal.Current returns apppool on IIS
  • Unable to use reactive element in my shiny app
  • java string with new operator and a literal
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How can I use threading to 'tick' a timer to be accessed by other threads?