0

I want to free memory after using an object ('ii', in the following program) in c++:

#include <iostream>
#include <armadillo>

using namespace std;
using namespace arma;

int main()
{
    cx_mat ii(2,2,fill::eye);
    cout << ii <<endl;
    free (ii);
    return 0;
}

But after compiling, I encounter to the following error:

error: cannot convert ‘arma::cx_mat {aka arma::Mat<std::complex<double> >}’ to ‘void*’ for argument ‘1’ to ‘void free(void*)’

can any body guide me?

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
Haj Nasser
  • 304
  • 2
  • 14
  • 3
    `ii` has "automatic storage duration", so its memory is released when the function returns. If your book or tutorial suggested that you do it manually, get a new one. If you haven't got a book, get one. – molbdnilo May 30 '15 at 20:33
  • You seem to be lacking some very basic knowledge. You should read a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Baum mit Augen May 30 '15 at 20:35

3 Answers3

2
cx_mat ii(2,2,fill::eye);

That's allocated on the stack, you can't free it, it will be destroyed when your program exits the scope.

http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

Maresh
  • 4,644
  • 25
  • 30
1

You can only free pointers holding an address returned by malloc, calloc or realloc. Nothing else. In particular, no matrices.

You also should not need to use free in C++, ever.

In your case, you do not need to do anything to free the memory, the destructor of the matrix will take care of that.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
1

The reason you're getting the error you're getting is because you're not passing a pointer to the function.

However, free requires that you pass a pointer that has been returned by malloc, calloc, or realloc, otherwise undefined behavior occurs.

The memory of your object will be freed when your function returns, or exits.