简体   繁体   中英

Free memory in c++ (armadillo)

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?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM