何时释放 C 代码中的内存?
例如,当我在 while 循环外部分配内存时,可以在其中释放内存吗? 这两个代码等效吗?
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
free(memory);
}
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
}
free(memory);
When I alloc memory outside a while loop for example, is it okay to free it inside it ?
Are these two codes equivalent ?
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
free(memory);
}
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
}
free(memory);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(6)
人生百味2024-08-24 13:19:52
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
free(memory);
}
这会崩溃。您将指针设置为内存位置 10,然后要求系统释放内存。即使在虚拟地址空间的疯狂世界中,您之前分配的某些内存也极不可能恰好从 10(十六进制的 0xA)开始。此外,如果 malloc 失败,则没有分配内存,因此不需要释放它。
int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
memory=10;
}
free(memory);
这也是一个错误。如果 malloc 失败,则将指针设置为 10 并释放该内存。 (和以前一样。)如果 malloc 成功,那么您将立即释放内存,这意味着分配它是没有意义的!现在,我想这只是为了表达要点而简化的示例代码,并且这在您的实际程序中不存在? :)
为人所爱2024-08-24 13:19:52
首先,你只能释放它一次。因此,如果您想在循环内释放它(正如您的问题所建议的那样),第二个解决方案是唯一正确的方法。
如果您想在 if 语句中释放它,这两种解决方案在技术上都是正确的。然而,始终释放您使用的内存是一个好习惯,这样在任何 if 语句之外的末尾总是释放内存会更容易。
所以我的建议是:无论你想做什么:总是在任何循环/if语句之外释放内存(当然假设你不再需要它)。我通常在最后使用它的函数末尾释放它,但这实际上取决于函数本身,它的长度,......
尝试找到你的做事方式并坚持下去:它会为你节省很多无用的东西大脑时间(这真的很宝贵)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
是的,它们是等价的。如果分配不成功,您不必调用
free()
。请注意,
memory
是指向int
的指针,并且您必须取消引用它才能将某些内容分配给它的内存块;Yes, they are equivalent. You do not have to call
free()
if allocation did not succeed.Pay attention, that
memory
is pointer toint
and you have to dereference it to assign something to its memory block;