如何释放记忆?

时间:2014-04-27 10:10:33

标签: c memory-management memory-leaks

我正在创建这样的变量:

    pthread_t *thread;
    struct thread_data *data;

    //allocate space for threads and their data
    thread = malloc(num_threads*sizeof(*thread));
    data = malloc(num_threads*sizeof(*data));

在我完成它们之后,我试图释放内存如下:

    //uuu... there is no garbage collector :P
    for (unsigned long i=0;i<num_threads;i++){
        free(&thread[i]);
        free(&data[i]);
    }

但是,我收到一个无效的指针错误。我对c有点新意,所以感谢任何指导。

P.S。:这就是结构的样子。

struct thread_data{
    int base,           //base term from which computation will start
        num_terms;      //numer of terms to compute
    double result;
};

3 个答案:

答案 0 :(得分:3)

malloc()的每次通话都应与free()的一次通话完全匹配。

因此修改代码以释放问题中分配的内存,如下所示:

    free(thread);
    free(data);

更新

请注意,malloc()返回的值必须完全传递给free()

答案 1 :(得分:1)

你只需要做

free(thread);
free(data);

free函数释放其参数指向的内存块。有关块大小的信息存储在内部,您不需要free动态分配的数组的每个元素。

因此,当malloc的返回值传递给free时,它会释放分配的整个内存块。

答案 2 :(得分:0)

在这种情况下,它会发现您打算一次性删除所有线程和数据元素,因此接受的答案代表;但如果您确实想要在不同时间释放单个线程和数据项,则必须单独分配。例如:

pthread_t** thread;  // Dynamic array of pointers to pthread_t

// Allocate pthread_t* array
threads = malloc(num_thread * sizeof(*thread));

// Allocate pthread_t elements
for( i = 0; i < num_threads; i++ )
{
    thread[i] = malloc( sizeof(*thread[i]) ) ;
}

// Similarly for data...

清理更加微妙(也许容易出错):

free( thread[i] ) ;
thread[i] = 0 ;  // Set pointer to null so element cannot be used after deletion

如果删除了所有线程元素,则可以删除线程指针数组:

free( thread ) ;

您可以清理所有操作:

for( i = 0; i < num_threads; i++ )
{
    free( thread[i] ) ;
    thread[i] = 0 ;
}
free( thread ) ;
thread = 0 ;

释放空指针是安全的,因此无需测试先前是否已删除某个元素,但在使用它之前需要对其进行测试。

请注意,取消引用空指针会被特意捕获为运行时错误,而取消引用过时指针会产生非确定性结果,并且在您进行某些无关更改的那一天导致代码时,通常会在代码中不被注意令人莫名其妙地崩溃 - 所以最好在解除分配后将指针设置为0 - 它将允许更早地检测到一些错误并且更容易修复。

相关问题