| 1 |
.. title:: clang-tidy - bugprone-string-literal-with-embedded-nul |
| 2 |
|
| 3 |
bugprone-string-literal-with-embedded-nul |
| 4 |
========================================= |
| 5 |
|
| 6 |
Finds occurrences of string literal with embedded NUL character and validates |
| 7 |
their usage. |
| 8 |
|
| 9 |
Invalid escaping |
| 10 |
---------------- |
| 11 |
|
| 12 |
Special characters can be escaped within a string literal by using their |
| 13 |
hexadecimal encoding like ``\x42``. A common mistake is to escape them |
| 14 |
like this ``\0x42`` where the ``\0`` stands for the NUL character. |
| 15 |
|
| 16 |
.. code-block:: c++ |
| 17 |
|
| 18 |
const char* Example[] = "Invalid character: \0x12 should be \x12"; |
| 19 |
const char* Bytes[] = "\x03\0x02\0x01\0x00\0xFF\0xFF\0xFF"; |
| 20 |
|
| 21 |
Truncated literal |
| 22 |
----------------- |
| 23 |
|
| 24 |
String-like classes can manipulate strings with embedded NUL as they are keeping |
| 25 |
track of the bytes and the length. This is not the case for a ``char*`` |
| 26 |
(NUL-terminated) string. |
| 27 |
|
| 28 |
A common mistake is to pass a string-literal with embedded NUL to a string |
| 29 |
constructor expecting a NUL-terminated string. The bytes after the first NUL |
| 30 |
character are truncated. |
| 31 |
|
| 32 |
.. code-block:: c++ |
| 33 |
|
| 34 |
std::string str("abc\0def"); // "def" is truncated |
| 35 |
str += "\0"; // This statement is doing nothing |
| 36 |
if (str == "\0abc") return; // This expression is always true |