Reputation: 43
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.
Upvotes: 4
Views: 703
Reputation: 1287
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 free
d 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.
Upvotes: 7
Reputation: 95
You can't access a variable you freed after freeing it. free() does not delete the value for the place in memory it simply lets the system know that you have deallocated it and that it can be used and written over.
Upvotes: 0