2

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.

JeffR
  • 765
  • 2
  • 8
  • 23
  • 2
    I would use `SecureZeroMemory` only if I was dealing with sensitive information in memory, in this case... – Leonardo Alves Machado Sep 29 '17 at 20:17
  • This [question](https://stackoverflow.com/questions/18944026/when-should-securezeromemory-be-used) might help you – Leonardo Alves Machado Sep 29 '17 at 20:28
  • Thanks, but that question does not examine the free() functin *in conjunction with* SecureZeroMemory() - that question is only looking at SecureZeroMemory, which is different than what I'm asking. – JeffR Sep 30 '17 at 14:04
  • What is "free/=NULL"? What do you mean by that? You flagged one of the comments here suggesting that this isn't a duplicate, but it's pretty clearly a duplicate to me. Free doesn't clear memory in any way, and setting a pointer to null does absolutely nothing. If you want to clear the memory, then you need to call SecureZeroMemory(), which is exactly what the answers to the proposed duplicate say. – Cody Gray - on strike Sep 30 '17 at 14:24
  • "free/=NULL' is shorthand for "free(x);x=NULL;" Thanks, your reply just answered my original question and confirms that the other article simply explains SecureZeroMemory() which is not what I'm asking. – JeffR Sep 30 '17 at 16:03
  • and the 'free()' function is not even mentioned in that other article...which is what I am asking. – JeffR Sep 30 '17 at 16:14

1 Answers1

2

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.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18
  • 1
    "Bit generally it doesn't do any harm to shred memory before freeing it." Other than waste time. If it was worth doing a zero on every free, then the standard library would do it for you. In 99% of cases, this is not necessary. – Cody Gray - on strike Sep 30 '17 at 14:25