0
Why does free() clear the contents of a memory location? {C}
Suppose this code: char *k = malloc(1); *k = 'a'; free(k); putchar(k); Why does free() clear the contents at the memory location at 'k'? I had thought that free() just de-allocated the memory space. Why clear its contents? In my opinion, this would tend to make the code run slower.
11 Réponses
+ 2
I don't know why 0 is stored in dangling pointer.
But this is not the case in mine PC. After freeing memory 'k' is still stored in unlocated memory as garbage.
And when I allocate new memory after freeing I got 'k' as garbage value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ch = malloc(1);
*ch = 'S';
printf("ch = %d\n", *ch);
free(ch);
printf("ch = %d\n", *ch);
}
+ 2
Calvin Thomas
I tested on PC a long time ago when I learned about dynamic memory.
I also tested on Android (CxxDroid) and 0 is not stored in memory after freeing it
+ 1
🌀 Shail Murtaza شعیل مرتضیٰ Oh, so it's a SoloLearn issue. Thank you for testing it in your PC.
0
Infinity Won't the new data overwrite the old garbage data? Why "nullify" the old data?
0
Infinity So what's the point in clearing that memory block? I see no advantage in that.
0
Infinity But the heap space allocated to one process can't be used by another process (at least until the present one terminates), right? Personally, I find no issue with garbage values, as they can be overwritten. In the rare cases, which are anyway present (like, declaring an integer array with all 0s) calloc() can be used. Then why should free() clear the memory block? Thanks for deciding to help me on this matter.
0
Infinity I see, but the real question was why free() should clear the memory block, apart from making the program more memory efficient. Thanks for the help, as I think that the solution to this question is however, pretty irrelevant.
0
Thanks for mentioning another user here.
0
Infinity What I had meant by the last sentence was that my question is pretty irrelevant.
0
Infinity I see, sorry for the misunderstanding caused. Thank you very much for helping me.
0
🌀 Shail Murtaza شعیل مرتضیٰ I see.