Reputation: 304
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?
Upvotes: 0
Views: 1552
Reputation:
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.
Upvotes: 1
Reputation: 4712
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
Upvotes: 2
Reputation: 50053
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.
Upvotes: 1