Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using free on nested structures

Tags:

c

malloc

free

How do I free the 'v struct' on the next 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.

}

The output is:
q1 = (1.000000, 2.000000, 2.000000, 2.000000)
q1 = (0.000000, 2.000000, 2.000000, 2.000000)
So, I am not deleting the pointer to v.
Also, Is my allocation ok?

Edit: Thank you for all your responses!
This is just a small sample of the actual program, I was not trying to use the pointer after freeing it. I just noticed the persistence of the memory and wanted to know if I had a memory leak and how to avoid it.

like image 329
Newbie Avatar asked Mar 07 '23 19:03

Newbie


1 Answers

You have a misconception. free() is not required to clear the contents of the memory you allocated, and free() does not change the address in memory to which the pointer q1Ptr is pointing to. free() just returns the resources to the operating system (or whatever allocated the memory to you). The values that assigned to that variable can persist and are not guaranteed to be zeroed out by free(). The fact that you are still seeing some of the values you assigned after the free() call is not an indication that the free() call failed.

However, using a pointer to memory that has been freed causes undefined behavior, because it is still pointing to memory you had allocated but it is no longer yours to use or access. In your system it seems OK this one time, but you cannot rely on that.

like image 144
Daniel Avatar answered Mar 10 '23 12:03

Daniel