简体   繁体   中英

malloc and free when using reassign pointer

Please, correct me if I'm wrong. In pseudo code bellow I create space for 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 . 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM