如何在下一个程序中释放“v 结构”?

#include <stdio.h>
#include <stdlib.h>

struct Quaternion{
  double r;
  struct Q_vec{
    double x;
    double y;
    double z;
  } v;
};

int main(void){

  struct Quaternion* q1Ptr = malloc(sizeof(struct Quaternion));
  q1Ptr->r = 1.0;
  q1Ptr->v.x = 2.0;
  q1Ptr->v.y = 2.0;
  q1Ptr->v.z = 2.0;

  printf("%s = (%f, %f, %f, %f)\n", "q1", q1Ptr->r, q1Ptr->v.x, q1Ptr->v.y, q1Ptr->v.z);

  free(q1Ptr);

  printf("%s = (%f, %f, %f, %f)\n", "q1", q1Ptr->r, q1Ptr->v.x, q1Ptr->v.y, q1Ptr->v.z);
  //Doesn't prints 'r', but prints x, y and z.

}

输出是:
q1 = (1.000000, 2.000000, 2.000000, 2.000000)
q1 = (0.000000, 2.000000, 2.000000, 2.000000)
所以,我不会删除指向 v 的指针。
另外,我的分配好吗?

编辑:感谢您的所有回复!
这只是实际程序的一个小示例,我并没有在释放指针后尝试使用它。我只是注意到内存的持久性,想知道我是否有内存泄漏以及如何避免它。

最佳答案

你有一个误解。 free() 不需要清除你分配的内存的内容,free() 不会改变指针 q1Ptr 指向的内存地址。 free() 只是将资源返回给操作系统(或任何分配给您的内存)。分配给该变量的值可以持久存在,并且不能保证被 free() 清零。在 free() 调用之后您仍然看到您分配的一些值的事实并不表示 free() 调用失败。

但是,使用指向内存的指针 free d 会导致未定义的行为,因为它仍然指向您已分配的内存,但不再是您使用或访问的内存。在您的系统中,这一次似乎没问题,但您不能依赖它。

关于c - 在嵌套结构上使用 free,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48996845/

10-11 21:19
查看更多