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()<
The original C philosophy was to have keep implicit effects to an absolute minimum. If a programmer wants a pointer zeroed after the memory pointed to is freed, that's what the programmer should write. Those of us who do often use a macro like this one:
#define FREE(P) ((void)(free((P)), (P) = NULL))
Of course if the expression passed to FREE
has side effects, one has just opened a large can of worms...
C why is the memory not explictly set to zero in the free implementation .
Because of speed.
Because after we free the memory any how we set it to zero after freeing.
Eh?
There's also bzero(3).
C was originally designed as a system implementation language, and so C operations are generally as fast and as close to the metal as is practical. One key point in the design philosophy is that you can take several fast operations and make them into one slower and safer operation, but you can't take slower and safer operations and make a faster one.
If you want a zero-and-free function, you can write one, and use it instead of free()
. If you're concerned with security, I'd recommend it.
Once you free memory using free(), the value & the memory allocated at that particular address gets deleted (freed) but the pointer still points to that address. If you try to de-reference that pointer you will get Segmentation fault or Bus error. So, its safe to assign NULL value to the pointer once the memory pointed by the pointer is freed. You may refer < Setting variable to NULL after free >
free() doesn't release memory back to the OS - it releases back to the process's heap manager. For efficiency reasons, it is not zero'd out.
When a process allocates virtual memory, most OS's will hand it a zero'd page. This prevents memory from "leaking" from one process to the other and causing a security issue like you mention.
If you have data in your process that you don't want to keep in memory (for example, a user's password), you are responsible for zeroing it out. Windows provides the SecureZeroMemory API for this.