2016-04-08 00:16:36 +08:00
|
|
|
.. title:: clang-tidy - misc-string-literal-with-embedded-nul
|
|
|
|
|
|
|
|
misc-string-literal-with-embedded-nul
|
|
|
|
=====================================
|
|
|
|
|
2016-08-29 04:33:42 +08:00
|
|
|
Finds occurrences of string literal with embedded NUL character and validates
|
2016-04-08 00:16:36 +08:00
|
|
|
their usage.
|
|
|
|
|
|
|
|
Invalid escaping
|
2016-08-27 01:46:51 +08:00
|
|
|
----------------
|
2016-04-08 00:16:36 +08:00
|
|
|
|
|
|
|
Special characters can be escaped within a string literal by using their
|
|
|
|
hexadecimal encoding like ``\x42``. A common mistake is to escape them
|
|
|
|
like this ``\0x42`` where the ``\0`` stands for the NUL character.
|
|
|
|
|
2016-08-27 01:46:51 +08:00
|
|
|
.. code-block:: c++
|
2016-04-08 00:16:36 +08:00
|
|
|
|
|
|
|
const char* Example[] = "Invalid character: \0x12 should be \x12";
|
|
|
|
const char* Bytes[] = "\x03\0x02\0x01\0x00\0xFF\0xFF\0xFF";
|
|
|
|
|
|
|
|
Truncated literal
|
2016-08-27 01:46:51 +08:00
|
|
|
-----------------
|
2016-04-08 00:16:36 +08:00
|
|
|
|
2016-08-27 01:46:51 +08:00
|
|
|
String-like classes can manipulate strings with embedded NUL as they are keeping
|
|
|
|
track of the bytes and the length. This is not the case for a ``char*``
|
|
|
|
(NUL-terminated) string.
|
2016-04-08 00:16:36 +08:00
|
|
|
|
|
|
|
A common mistake is to pass a string-literal with embedded NUL to a string
|
|
|
|
constructor expecting a NUL-terminated string. The bytes after the first NUL
|
|
|
|
character are truncated.
|
|
|
|
|
2016-08-27 01:46:51 +08:00
|
|
|
.. code-block:: c++
|
2016-04-08 00:16:36 +08:00
|
|
|
|
|
|
|
std::string str("abc\0def"); // "def" is truncated
|
|
|
|
str += "\0"; // This statement is doing nothing
|
|
|
|
if (str == "\0abc") return; // This expression is always true
|