1

Is there a difference in benefit for "zeroing out" a char array so it doesn't stay in memory using Arrays.fill(password, 0) instead of using password = null? I'm not asking why use a char array instead of a String. I'm asking why set the values to 0 instead of setting the array to null. Is it because setting the values to 0 immediately changes the value in memory, while null doesn't immediately change the value to null in memory, but instead just waits for it to be garbage collected? Would it make sense to set the values to 0 then immediately set it to null as well so that it gets garbage collected, instead of sitting around as an array of 0's?

Artanis
  • 561
  • 1
  • 7
  • 26
  • Setting a variable to null doesn't erase the object from memory until the GC kicks in. – shmosel Dec 21 '18 at 22:23
  • I could have sworn someone asked a question about this before, but I would think zeroing out the array would be better than re-referencing the object, as you can be sure that the memory has been changed and doesn't have to wait until it's garbage collected. – Jacob G. Dec 21 '18 at 22:23
  • @shmosel That was the question I was referring to, thanks! – Jacob G. Dec 21 '18 at 22:24
  • I'm not asking why use a char array instead of a string. I'm asking why set the values to 0 instead of setting the array to null. None of those answers clarify this difference. – Artanis Dec 21 '18 at 22:33
  • Did you see my answer? – Bsquare ℬℬ Dec 22 '18 at 10:26
  • It's the same reason. Because reference cleanups have to wait for the GC. – shmosel Dec 24 '18 at 05:33

1 Answers1

0

No, whatever the value of each char, the array is still maintain in memory and thus consume it.

Defining the reference to null may lead to GC election if it was the last reference to this array.

On the other hand, if you have security concerns, resetting each char before freeing the reference is a best practice.

You can read more about Why is char[] preferred over String for passwords?

Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
  • 1
    For the benefit of others: "*may*" is a keyword here. There is no guarantee GC will be invoked. – PM 77-1 Dec 21 '18 at 22:27
  • @zeratul On Stackoverflow you can give [up-vote](https://stackoverflow.com/help/privileges/vote-up) to people's helpful answers to thank them and select any one of the answer as [correct answer](https://stackoverflow.com/help/someone-answers) too out of all. – Bsquare ℬℬ Jan 14 '19 at 13:03