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

1  #include <cstring>
2  #include <iostream>
3  
4  class C {
5    int scalingFactor;
6    int otherData;
7  
8  public:
9    C() : scalingFactor(1) {}
10 
11   void set_other_data(int i);
12   int f(int i) {
13     return i / scalingFactor;
14   }
15   // ...
16 };
17 
18 void f() {
19   C c;
20 
21   // ... Code that mutates c ...
22 
23   // Reinitialize c to its default state
24   std::memset(&c, 0, sizeof(C));       //uncompliant code
25 
26   std::cout << c.f(100) << std::endl;
27 }