Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added explanation of why strncpy() is safe.

...

Code Block
bgColor#ffcccc
langcpp
#include <iostream>
#include <memory>
#include <cstring>
 
int main(int argc, const char *argv[]) {
  const char *s = "";
  if (argc > 1) {
    enum { BufferSize = 32 };
    try {
      std::unique_ptr<char[]> buff(new char[BufferSize]);
      // ...
      s = std::strncpy(buff.get(), argv[1], BufferSize - 1);
    } catch (std::bad_alloc &) {
      // Handle error
    }
  }

  std::cout << s << std::endl;
}

Note that this code does not create a non-null-terminate byte string, despite its use of strncpy(). This is because it leaves the final char in the buffer set to its default value, which is set to 0 by operator new.

Compliant Solution (std::unique_ptr)

...