CERT.OOP.CSTD_FUNC_USE

Prefer special member functions and overloaded operators to C Standard Library functions.

Prefer special member functions and overloaded operators to C Standard Library functions. These C functions includes: memset(), memcpy(), memmove(), strcpy(), memcmp(), strcmp(). You should use C++ equivalent functionality to replace them.

Vulnerability and risk

Several C standard library functions perform bytewise operations on objects. For instance, std::memcmp() compares the bytes comprising the object representation of two objects, and std::memcpy() copies the bytes comprising an object representation into a destination buffer. However, for some object types, it results in undefined or abnormal program behavior.

Mitigation and prevention

You should use C++ equivalent functionality to replace them. For example, to use the class constructor or overloaded operators such as operator<(), operator>(), operator==(), or operator!=().

Example

Copy
  #include <cstring>
  #include <iostream>
  
  class C {
    int scalingFactor;
    int otherData;
  
  public:
    C() : scalingFactor(1) {}
 
   void set_other_data(int i);
   int f(int i) {
     return i / scalingFactor;
   }
   // ...
 };
 
 void f() {
   C c;
 
   // ... Code that mutates c ...
 
   // Reinitialize c to its default state
   std::memset(&c, 0, sizeof(C));       //uncompliant code
 
   std::cout << c.f(100) << std::endl;
 }