Search code examples
cfreesecurezeromemory

Is free/=NULL enough to clear memory, or should SecureZeroMemory be placed immediately before it?


What's the best way to clear out this allocated memory?

  1. Is free/=NULL all that's needed
  2. Does SecureZeroMemory before doing a free/=NULL add to the security of the code?
  3. Or, is adding SecureZeroMemory overkill?

Here's my code:

        DWORD tLen = 128;
        BYTE *pbData = (BYTE *)malloc(tLen);
        memcpy(pbData, chBuffer, tLen);

        // ...work done here...

        // Clear it
        SecureZeroMemory(pbData, tLen);
        free(pbData);pbData=NULL;

Thanks!

EDIT: This question is not a duplicate of the question some people have said it is. It is not asking when to use SecureZeroMemory, but the best practice when used with free/=NULL.


Solution

  • It depends what your program is doing. If someone else can look at a buffer of freed memory, is that a concern to you? If the memory contains bank account details, I'd say that it is. If it contains settings for a video game, maybe not (depending on how determined your users are to cheat).

    Bit generally it doesn't do any harm to shred memory before freeing it.