0

I have created that function to handle a secret

#define SIZE 100
void secret_handle(void)
{
    char secret[SIZE] = {0}; //initalize the array with zeros
    load_secret(secret, SIZE);
    // some code to manipulate the secret
    memset(secret, 0, SIZE); //clean up after using it
}

I thought that I shouldn't worry about the memset function because the array will disappear anyway from the run-time stack when the function secret_handle is quit. is there a thing I miss? Thank you all.

ylev
  • 27
  • 5
  • 1
    You won't be able to access it using Standard C++, but it will still be there, on the stack. –  Nov 03 '18 at 18:22
  • I think this is related: https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords – Aykhan Hagverdili Nov 03 '18 at 18:24
  • 1
    Without the memset, some unscrupulous code could sniff the stack and see the remnants there. From a C++ standpoint, doing so is in the undefined behavior zone, but from a debugger or assembler standpoint the stack could be rummaged through. Depending on platform. – Eljay Nov 03 '18 at 18:25
  • 1
    I'll bet your compilers optimizer will remove that `memset` since, from a C++ standpoint, it doesn't do anything. – Jesper Juhl Nov 03 '18 at 18:29
  • Things typically disappear from the stack by adjusting stack pointer, not by performing some sort of stack cleanup. So without (optimization-aware) safe `memset` call `secret` content will most likely be preserved until some other function reuses the stack and overwrites it. – user7860670 Nov 03 '18 at 18:54
  • You can probably force the array to be scrubbed by using `std::fill_n` with the array cast to a `volatile` pointer. – StoryTeller - Unslander Monica Nov 03 '18 at 19:05

0 Answers0