All of the stuff I could find referring to freeing 'double' pointers refers to freeing pointers to pointers, which is not what I am talking about. I already figured out how to do that.
It might not even be a big thing at all, but I noticed that when I free()
an int
, char
, or float
pointer, the value is removed or replaced with a garbage value, but when I free()
a double
pointer, the value remains the same.
Here's the code I tested this with:
int main()
{
int *p_a = malloc(sizeof(int));
*p_a = 1;
char *p_b = malloc(sizeof(char));
*p_b = 'b';
float *p_c = malloc(sizeof(float));
*p_c = 3.565;
double *p_d = malloc(sizeof(double));
*p_d = 7.77;
printf("Before 'free()':\n");
printf("A: %p\t%d\n", p_a, *p_a);
printf("B: %p\t%c\n", p_b, *p_b);
printf("C: %p\t%g\n", p_c, *p_c);
printf("D: %p\t%g\n", p_d, *p_d);
free(p_a);
free(p_b);
free(p_c);
free(p_d);
printf("\nAfter 'free()':\n");
printf("A: %p\t%d\n", p_a, *p_a);
printf("B: %p\t%c\n", p_b, *p_b);
printf("C: %p\t%g\n", p_c, *p_c);
printf("D: %p\t%g\n", p_d, *p_d);
return 0;
}
This produced the following output:
Before 'free()':
A: 0x8f2e008 1
B: 0x8f2e018 b
C: 0x8f2e028 3.565
D: 0x8f2e038 7.77
After 'free()':
A: 0x8f2e008 0
B: 0x8f2e018
C: 0x8f2e028 1.46175e-33
D: 0x8f2e038 7.77
Is that normal? My understanding of how malloc()
and free()
work is that when you malloc()
a pointer, you set aside some bytes of memory for the pointer to point to. This is put on the heap
, where it cannot be accessed, and it will not come off the heap
until it is free()
d or a memory clean-up is triggered on the computer, which is not controlled by the user. So, when you free()
a pointer, you basically get rid of the association between the pointer and the address it points to, allowing that memory to be used later on.
Given all that, why is the double
pointer still pointing to the same value?
Now that I think about it, why do the pointers have an address at all after the free()
s?
As I am a beginner to C
, any and all wisdom and knowledge is much appreciated. Thank you for your time.
EDIT: After further testing and meddling, I found that if you enter a number that has more than 6 digits and rounds up on the last one (eg. 777.7777) for the double
, after it is free()
d it loses its rounding.
To illustrate:
Before 'free()':
D: 0x8f2e038 777.778
After 'free()':
D: 0x8f2e038 777.777
This supports @rodrigo's hypothesis (in the comments) that, because the double
is 8 bytes - as opposed to int
, char
and float
's 4 bytes - free()
only modifies the first 4 bytes, so it does not lose all of its data.
Thanks everyone for your help!