Using free on nested structures

How do I free the 'v struct' in the following program?

#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.

}

Conclusion:
  q1 = (1.000000, 2.000000, 2.000000, 2.000000)
  q1 = (0.000000, 2.000000, 2.000000, 2.000000)
So, I do not delete the pointer to v.
Also, is there a selection in the order?

Edit: Thanks for all your answers!
This is just a small example of a real program, I did not try to use the pointer after it was released. I just noticed the persistence of memory and wanted to know if I had a memory leak and how to avoid it.

+4
source share
2 answers

. free() , free() , q1Ptr. free() ( , ). , , free(). , - , free(), , free() .

, free d, undefined, - , . , , .

+6

, . free() , , .

0

Source: https://habr.com/ru/post/1694151/


All Articles