Home > Enterprise >  Assign one allocated pointer to another allocated pointer
Assign one allocated pointer to another allocated pointer

Time:04-21

Is the memory that t2 points to still reachable after the assignment?

#include<stdio.h>

int main()
{
  double *t1 = (double *)calloc(6, sizeof(double));
  double *t2 = (double *)calloc(6, sizeof(double));
  
  t2=t1;

  free(t1);

  return 0;
}

Is the above code recommended? Will it cost memory leak? Or, does the memory t2 points to just align with what t1 points to in this case?

Should I just simply use double *t3 = t1 instead?

CodePudding user response:

Is the memory that t2 points to still reachable after the assignment?

No

Is the above code recommended?

No.

Will it cost memory leak?

Yes, the memory pointed to by t2 is leaked.

Or, does the memory t2 points to just align with what t1 points to in this case?

It does but the original calloc memory is lost.

Should I just simply use double *t3 = t1 instead?

Yes if you just want another pointer variable to the same address.

CodePudding user response:

After these 2 lines

double *t1 = (double *)calloc(6, sizeof(double));
double *t2 = (double *)calloc(6, sizeof(double));
  • t1 is the only way to refer to the memory allocated in the first line
  • t2 is the only way to refer to the memory allocated in the second line

SO if you want to use and ultimately free those chunks, you need those pointer values somewhere.

So

t2=t1;

Now loses all access to the second chunk. You have no way to refer to it. There is nothing 'special' about 't1' and 't2' you can do:

 double * foo = t1;
 double * bar = t2;
 t2 = t1;
 t1 = NULL;

or whatever you like with them, because now you have those values stored in 'foo' and 'bar'. You just have to store those pointer values somewhere.

  • Related