【发布时间】:2016-03-10 05:18:57
【问题描述】:
所以这是在运行基于 Debian 的 Linux 操作系统的 x86 机器上。我有以下被多次调用的函数。我不确定是否应该 free() temp 指针,或者我可以让函数保持原样。
int my_function (char *Data, int Data_size) {
void *temp;
Data_size = 7000;
// Allocate a huge array to store a line of the datalogger
//
temp = (char *) realloc( Data, Data_size);
if (temp == NULL)
{
printf("Reallocate Data ERROR\n");
free(Data);
return -1;
}
Data = temp;
// Do something with the Data
return 1;
}
【问题讨论】:
-
你不应该。
free()用于告诉操作系统您不再使用具有给定地址的内存。既然你把那块内存给了“数据”,你就不应该释放它。但是,当您在程序的某些部分停止使用“数据”时,您应该调用free()。 -
嘿,谢谢。因此,如果我在函数内使用“数据”并且不再需要它,我应该在退出函数之前释放(数据)和释放(临时)?
-
Data 是一个指针, temp 也是一个指针,它们指向同一个内存块,所以你不需要释放它们。当函数完成时, temp 将被销毁,但它指向的数据将在内存中保持活动状态。由于 Data 指向该内存块,因此只有在使用完
Data后才应调用free()。 -
此代码泄漏内存。
Data = temp;不会告诉调用代码有关temp的任何信息。 C 使用按值传递。
标签: c linux pointers free realloc