brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.5 KiB · de10da2 Raw
62 lines · plain
1.. title:: clang-tidy - bugprone-suspicious-stringview-data-usage2 3bugprone-suspicious-stringview-data-usage4=========================================5 6Identifies suspicious usages of ``std::string_view::data()`` that could lead to7reading out-of-bounds data due to inadequate or incorrect string null8termination.9 10It warns when the result of ``data()`` is passed to a constructor or function11without also passing the corresponding result of ``size()`` or ``length()``12member function. Such usage can lead to unintended behavior, particularly when13assuming the data pointed to by ``data()`` is null-terminated.14 15The absence of a ``c_str()`` method in ``std::string_view`` often leads16developers to use ``data()`` as a substitute, especially when interfacing with17C APIs that expect null-terminated strings. However, since ``data()`` does not18guarantee null termination, this can result in unintended behavior if the API19relies on proper null termination for correct string interpretation.20 21In today's programming landscape, this scenario can occur when implicitly22converting an ``std::string_view`` to an ``std::string``. Since the constructor23in ``std::string`` designed for string-view-like objects is ``explicit``,24attempting to pass an ``std::string_view`` to a function expecting an25``std::string`` will result in a compilation error. As a workaround, developers26may 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 would42lead to a compilation error due to the explicit nature of the ``std::string``43constructor. Consequently, developers might opt for ``sv.data()`` to resolve the44compilation error, albeit introducing potential hazards as discussed.45 46Options47-------48 49.. option:: StringViewTypes50 51  Option allows users to specify custom string view-like types for analysis. It52  accepts a semicolon-separated list of type names or regular expressions53  matching these types. Default value is:54  `::std::basic_string_view;::llvm::StringRef`.55 56.. option:: AllowedCallees57 58  Specifies methods, functions, or classes where the result of ``.data()`` is59  passed to. Allows to exclude such calls from the analysis. Accepts a60  semicolon-separated list of names or regular expressions matching these61  entities. Default value is: empty string.62