1// RUN: %check_clang_tidy -std=c++17-or-later %s bugprone-suspicious-stringview-data-usage %t -- -- -isystem %clang_tidy_headers
2#include <string>
3
4struct View {
5 const char* str;
6};
7
8struct Pair {
9 const char* begin;
10 const char* end;
11};
12
13struct ViewWithSize {
14 const char* str;
15 std::string_view::size_type size;
16};
17
18void something(const char*);
19void something(const char*, unsigned);
20void something(const char*, unsigned, const char*);
21void something_str(std::string, unsigned);
22
23void invalid(std::string_view sv, std::string_view sv2) {
24 std::string s(sv.data());
25// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
26 std::string si{sv.data()};
27// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
28 std::string_view s2(sv.data());
29// CHECK-MESSAGES: :[[@LINE-1]]:26: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
30 something(sv.data());
31// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
32 something(sv.data(), sv.size(), sv2.data());
33// CHECK-MESSAGES: :[[@LINE-1]]:39: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
34 something_str(sv.data(), sv.size());
35// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
36 View view{.str: sv.data()};
37// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: result of a `data()` call may not be null terminated, provide size information to the callee to prevent potential issues
38}
39
40void valid(std::string_view sv) {
41 std::string s1(sv.data(), sv.data() + sv.size());
42 std::string s2(sv.data(), sv.data() + sv.length());
43 std::string s3(sv.data(), sv.size() + sv.data());
44 std::string s4(sv.data(), sv.length() + sv.data());
45 std::string s5(sv.data(), sv.size());
46 std::string s6(sv.data(), sv.length());
47 something(sv.data(), sv.size());
48 something(sv.data(), sv.length());
49 ViewWithSize view1{.str: sv.data(), .size: sv.size()};
50 ViewWithSize view2{.str: sv.data(), .size: sv.length()};
51 Pair view3{.begin: sv.data(), .end: sv.data() + sv.size()};
52 Pair view4{.begin: sv.data(), .end: sv.data() + sv.length()};
53 Pair view5{.begin: sv.data(), .end: sv.size() + sv.data()};
54 Pair view6{.begin: sv.data(), .end: sv.length() + sv.data()};
55 const char* str{sv.data()};
56}
57

source code of clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-stringview-data-usage.cpp