我有一个内存分配问题。如果我在char*
块中声明了else
,则意味着当char*
块执行完毕时,else
被破坏了。 else
块位于while
循环中,因此它将迭代多次。但是,如果在char*
块中声明的else
别名为malloc'd
变量,如下面的示例所示,该怎么办。我的问题是我该如何收费?我觉得好像我释放了temp char*
变量一样,会引起分段错误,因为我也会释放我想保留的变量。如果真是这样,我对free
语句的位置不知所措。
char* print_path = NULL;
(剪断)
(while)
else{
char* temp_path = print_path;
int temp_size = strlen(temp_path)+strlen(file_name(child->fts_path))+1;
print_path = (char*)malloc(temp_size);
strcpy(print_path, temp_path);
strncat(print_path, file_name(child->fts_path), strlen(file_name(child->fts_path)));
printf("%s:\n\n", print_path);
}
(剪断)
我想指出的是,在知道不会再次执行该程序后,我在程序末尾释放了print_path。但是,我想释放的是循环的中间执行。任何帮助,将不胜感激。
谢谢!
最佳答案
看来free(temp_path)
是正确的事情。它应该像这样:
char * print_path = malloc(...); // "NULL" is also possible
while (condition)
{
if (...)
{
// ...
}
else
{
char * temp_path = print_path;
print_path = malloc(...);
free(temp_path);
}
}
free(print_path);
算法中的不变式是(或应该是)
print_path
始终指向动态平衡的内存。请注意,对于每个free
,我们如何精确地拥有一个malloc
。