UNUSED.FUNC.STL_EMPTY

Ignored return value of an STL object empty() method

The UNUSED.FUNC.STL_EMPTY checker detects and reports instances of calls to the empty() method of standard C++ container classes, in cases when the value returned from the call is ignored.

Vulnerability and risk

C++ containers from the standard library typically implement two distinct methods: clear() and empty(). The clear() method clears the contents of the container; the empty() method checks if the container has at least one element in it. Accidental confusion of these two methods can result in serious and hard-to-find algorithmic bugs. The empty() method returns a boolean value storing the result of the check. Ignoring this value is suspicious, and can indicate a mistake in the choice of the method name being called.

Vulnerable code example

In the following code, the programmer intent was to clear the contents of the container. Instead, they have called the empty() method that checks if the container is empty.

Copy
   void foo(std::vector<MyType>& v)
   {
       /* ... */
       v.empty();    // return value is ignored, indicating a logical mistake
   }

In this example, Klocwork reports the expression 'v.empty()' as an UNUSED.FUNC.STL_EMPTY defect.

Fixed code example

In the fixed code example, the programmer correctly calls the clear() method.

Copy
   void foo(std::vector<MyType>& v)
   {
       /* ... */
       v.clear();
   }

Related checkers