1

While reviewing a piece of C++ code I came across instances (reported by CPPcheck) where memset() was used on structures containing string members. I have come across a few references that talk about how this is not a good practice. I am unable to conclude if this behavior can result in a security risk.

references:

http://timmurphy.org/2013/01/23/is-it-safe-to-use-stdmemset-on-c-structs-and-classes/ https://stackoverflow.com/questions/6877281/memset-structure-with-stdstring-contained

My C++ skills are limited. My apologies if I am missing out of something obvious here.

3

I believe the issue lies with the fact that std::wstring is not necessarily a simple structure in the traditional C sense.

Instead it'll be a class with an internal state, structure and possible a vtable to class functions that are not necessarily visible to you.

So if you memset() the class you may end up destroying internal state and function pointers leading to undefined behaviour if you then try and use the class. And as we all know undefined behaviour is bad.

  • Thanks for the answer. Do you mean to say that this undefined behavior is only a risk if the class in question is then reused? – Shurmajee Sep 23 '16 at 18:06
  • @Shurmajee There is also the fact that you may end up leaking memory, which probably isn't very good for security even if you don't reuse the class. – JAB Sep 23 '16 at 18:49
  • This is also why you want to explicitly call an object's destructor before reusing its spot in a memory pool when using placement new. You want to ensure consistent state. – JAB Sep 23 '16 at 18:59
  • That may even have an analogous implication in plain C, e.g. if you screw up and do memset(p, 0, wcslen(p)) instead of memset(p, 0, strlen(p)) – grochmal Sep 24 '16 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.