Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Coding style conformance; typo fix

...

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 { BUFFER_SIZEBufferSize = 32 };
    try {
      std::unique_ptr<char[]> buff(new char[BUFFER_SIZEBufferSize]);
      // ...
      s = std::strncpy(buff.get(), argv[1], BUFFER_SIZEBufferSize - 1);
    } catch (std::bad_alloc &) {
      // Handle error
    }
  }

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

...

Code Block
bgColor#ccccff
langcpp
#include <iostream>
#include <memory>
#include <cstring>
 
int main(int argc, const char *argv[]) {
  std::unique_ptr<char[]> buff;
  const char *s = "";

  if (argc > 1) {
    enum { BUFFER_SIZEBufferSize = 32 };
    try {
      buff.reset(new char[BUFFER_SIZEBufferSize]);
      // ...
      s = std::strncpy(buff.get(), argv[1], BUFFER_SIZEBufferSize - 1);
    } catch (std::bad_alloc &) {
      // Handle error
    }
  }

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

...

Code Block
bgColor#ffcccc
langcpp
#include <string>
 
std::string someStringReturningFunctionstr_func();
void displayStringdisplay_string(const char *);
 
void f() {
  const char *str = someStringReturningFunctionstr_func().c_str();
  displayStringdisplay_string(str);  /* Undefined behavior */
}

...

In this compliant solution, a local copy of the string returned by someStringReturningFunctionstr_func() is made to ensure that string str will be valid when the call to displayStringdisplay_string() is made:

Code Block
bgColor#ccccff
langcpp
#include <string>
 
std::string someStringReturningFunctionstr_func();
void displayStringdisplay_string(const char *s);

void f() {
  std::string str = someStringReturningFunctionstr_func();
  const char *strcstr = str.c_str();
  displayStringdisplay_string(strcstr);  /* ok */
}

Noncompliant Code Example

...