将一个分配的指针分配给另一个分配的指针

Assign one allocated pointer to another allocated pointer

t2指向的内存在赋值后是否仍然可以访问?

#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;
}

上面的代码值得推荐吗?会导致内存泄漏吗?或者,在这种情况下,内存 t2 指向的内容是否与 t1 指向的内容对齐?

我应该只使用 double *t3 = t1 吗?

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

没有

Is the above code recommended?

没有

Will it cost memory leak?

是的,t2指向的内存泄露了

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

是的,但是原来的calloc记忆丢失了。

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

是的,如果你只是想要另一个指向同一地址的指针变量。

这两行之后

double *t1 = (double *)calloc(6, sizeof(double));
double *t2 = (double *)calloc(6, sizeof(double));
  • t1 是引用第一行分配的内存的唯一方式
  • t2 是引用第二行中分配的内存的唯一方法

所以如果你想使用并最终释放这些块,你需要在某处使用这些指针值。

所以

t2=t1;

现在失去对第二个区块的所有访问权限。你没有办法参考它。 关于 't1' 和 't2' 你无能为力 'special':

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

或您喜欢的任何内容,因为现在您已将这些值存储在 'foo' 和 'bar' 中。您只需将这些指针值存储在某处即可。