When we free()
memory in C, why is that memory not filled with zero? Is there a good way to ensure this happens as a matter of course when calling free()<
Zeroing out the memory block when freeing it will require extra time. Since most of time there's actually no need in it it is not done by default.
If you really need (say you used memory for storing a password or a cryptographic key) - call memset()
before freeing the block. Writing an utility function that chains memset()
and free()
is not a problem either.
memset(ptr, 0, size);
free(ptr);
i think you want this...
If I understand the question correctly the OP wants to not leave sensitive information "out there" in fear of it being compromised. As the previous posters pointed out freeing the memory before releasing it is the answer to wiping the data.
However, it is far from the answer to what the OP is trying to achieve. For starters zeroing the memory is 100% useless in securing your application. Even if the memory page is allocated to another running process, in most OSs this procedure is non-deterministic and no sane hacker will EVER use such a technique to compromise your data.
What a sane hacker would do is whack your program into a disassembler and debug through it until they figure out where the data is and then use it. Since a call to memset is bleedingly obvious once you are a competent disassemblerator(yes, disassemblerator :) ) our hypothetical hacker would just get to the data before memset happens.
To really answer your question. If you are trying to protect some sensitive data inside your C program you are getting in the domain that is far beyond normal C/C++ programmers(like myself) into realm of writing virtual machines for executing your data sensitive operations.
The fact that you even ask this question means that it would be reckless for you to develop something that requires this level of protection. Also it will absolutely not be the first stop in protecting your data. Pick the low hanging fruit first and there is plenty info on the web about that.
A very specific answer to the question "Why is the memory not set to 0 after freeing it?" is "Because the language specification does not define that behavior.
From the draft ANSI C spec: "The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation."
If you want the memory to be set to 0 when you free it, you'll have to do it yourself before you free()
it. If you try after you free()
it there are no guarantees that it hasn't been allocated again. For instance you can use memset() for that.
free()
doesn't guarantee that the memory will be cleared because C doesn't guarantee that malloc()
will return initialized memory. Either way you have to initialize it yourself after it's been allocated, so there's no point in clearing it when it's free()
'd
Because it would be a pure waste of time.