1.. title:: clang-tidy - bugprone-suspicious-stringview-data-usage 2 3bugprone-suspicious-stringview-data-usage 4========================================= 5 6Identifies suspicious usages of ``std::string_view::data()`` that could lead to 7reading out-of-bounds data due to inadequate or incorrect string null 8termination. 9 10It warns when the result of ``data()`` is passed to a constructor or function 11without also passing the corresponding result of ``size()`` or ``length()`` 12member function. Such usage can lead to unintended behavior, particularly when 13assuming the data pointed to by ``data()`` is null-terminated. 14 15The absence of a ``c_str()`` method in ``std::string_view`` often leads 16developers to use ``data()`` as a substitute, especially when interfacing with 17C APIs that expect null-terminated strings. However, since ``data()`` does not 18guarantee null termination, this can result in unintended behavior if the API 19relies on proper null termination for correct string interpretation. 20 21In today's programming landscape, this scenario can occur when implicitly 22converting an ``std::string_view`` to an ``std::string``. Since the constructor 23in ``std::string`` designed for string-view-like objects is ``explicit``, 24attempting to pass an ``std::string_view`` to a function expecting an 25``std::string`` will result in a compilation error. As a workaround, developers 26may be tempted to utilize the ``.data()`` method to achieve compilation, 27introducing potential risks. 28 29For instance: 30 31.. code-block:: c++ 32 33 void printString(const std::string& str) { 34 std::cout << "String: " << str << std::endl; 35 } 36 37 void something(std::string_view sv) { 38 printString(sv.data()); 39 } 40 41In this example, directly passing ``sv`` to the ``printString`` function would 42lead to a compilation error due to the explicit nature of the ``std::string`` 43constructor. Consequently, developers might opt for ``sv.data()`` to resolve the 44compilation error, albeit introducing potential hazards as discussed. 45 46.. option:: StringViewTypes 47 48 Option allows users to specify custom string view-like types for analysis. It 49 accepts a semicolon-separated list of type names or regular expressions 50 matching these types. Default value is: 51 `::std::basic_string_view;::llvm::StringRef`. 52 53.. option:: AllowedCallees 54 55 Specifies methods, functions, or classes where the result of ``.data()`` is 56 passed to. Allows to exclude such calls from the analysis. Accepts a 57 semicolon-separated list of names or regular expressions matching these 58 entities. Default value is: empty string. 59