vico
vico

Reputation: 18171

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);

Upvotes: 1

Views: 225

Answers (1)

Graeme Perrow
Graeme Perrow

Reputation: 57248

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.

Upvotes: 2

Related Questions