免费 GSL 矩阵的正确方法是什么?

What is the correct way to free GSL matrix?

我正在使用 C 中的 Gnu 科学库。来自 official documentation:

void gsl_matrix_free(gsl_matrix * m)

This function frees a previously allocated matrix m. If the matrix was created using gsl_matrix_alloc() then the block underlying the matrix will also be deallocated. If the matrix has been created from another object then the memory is still owned by that object and will not be deallocated.

这是什么意思?假设我有

gsl_matrix * get_me_a_matrix(void){
    gls_matrix * out =  gsl_matrix_alloc(10, 10); //here is the allocation
    //assign some values here
    return out;
}

并且在主函数中

int main(){
   gsl_matrix * my_matrix = get_me_a_matrix();
   //play around with my matrix here
   gsl_matrix_free(my_matrix);
   //is the memory free now?

}

调用 gsl_matrix_free 真的会释放内存吗,即使该对象已在另一个函数中分配?

是的,在您的代码中它会那样工作。由于您使用 gsl_matrix_alloc 分配了它, 您需要 使用 gsl_matrix_free 释放它。这与 mallocfree.

没有什么不同

引用摘录中的最后一句话指的是 you 获取指向 gsl_matrix 的指针,但它指向共享内存或部分内存由另一个对象,该内存不会被 gsl_matrix_free 释放,但是当您停止使用它时,您仍然要在指针上调用 gsl_matrix_free