【发布时间】:2013-10-07 23:07:46
【问题描述】:
我有以下代码:
void fn(char *string , int flag)
{
static char* array_of_strings[100];
static int index = 0;
if(flag)
{
array_of_strings[index] = (char *)malloc(10);
strcpy(array_of_strings[index] , string);
index++;
}
else
{
//How should I deallocate the memory here?
index--;
}
}
如果遇到 else 块,array_of_strings[index] 会发生什么?它会被自动释放还是会在 fn() 返回后保留?我是否应该使用这一行来代替评论:
array_of_strings[index] = 0;
或者我可以像这样使用 free():
free(array_of_strings[index]);
这会释放 malloc 分配的内存块吗?
【问题讨论】:
-
像往常一样,每个
malloc(或realloc等)都应该有一个对应的free。