【发布时间】:2020-12-30 21:27:58
【问题描述】:
我从来没有想过这个,但我有点好奇,但是如果我在这样的 if-else 语句中初始化一个指针呢?
if (true)
{
int *p=(int*)malloc (sizeof (int));
} // Will p be freed here?
// Can't free (p) here since it is not in this scope
我认为代码几乎可以说明我的问题的所有内容...我实际上有这样的想法,有必要在if 语句的末尾加上free(p),但是如果它在循环中呢?
for (int x=0; x<5; x++)
{
int *p=(int*)malloc (sizeof (int));
// Some code here
free (p); // Will p deallocated 5 times or just once?
}
【问题讨论】:
-
第一个是内存泄漏。第二个分配内存5次,释放5次,所以这个就ok了
标签: c if-statement pointers memory-management dynamic-memory-allocation