[英]malloc and free when using reassign pointer
Please, correct me if I'm wrong. 请,如果我错了,请纠正我。 In pseudo code bellow I create space for
j
. 在下面的伪代码中,我为
j
创建空间。 Of couse at the end I need to free space. 最后,我需要释放空间。 But if
j
was reaasigned to another variable it is not good to free variables anotherJob
spoace and I will have memory leak of j
anyway, because code is freeing anotherJob
. 但是,如果将
j
重新分配给另一个变量,则释放变量anotherJob
语句是不好的,无论如何我都会遇到j
内存泄漏,因为代码正在释放anotherJob
。 I'm right? 我是正确的?
j=malloc(sizeof(struct jobDetails));
...
j=anotherJob;
...
free(j);
Yes, you are correct. 是的,你是对的。 Unless you've saved the original value of
j
away somewhere else, it will get leaked. 除非您将
j
的原始值保存在其他地方,否则它将泄漏。 You don't likely want to free anotherJob
here since you don't know where it came from or if it's going to be free'd somewhere else. 您可能不想在这里释放
anotherJob
,因为您不知道它来自何处,或者是否会在其他地方释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.