| 1 |
.. title:: clang-tidy - bugprone-suspicious-memset-usage |
| 2 |
|
| 3 |
bugprone-suspicious-memset-usage |
| 4 |
================================ |
| 5 |
|
| 6 |
This check finds ``memset()`` calls with potential mistakes in their arguments. |
| 7 |
Considering the function as ``void* memset(void* destination, int fill_value, |
| 8 |
size_t byte_count)``, the following cases are covered: |
| 9 |
|
| 10 |
**Case 1: Fill value is a character ``'0'``** |
| 11 |
|
| 12 |
Filling up a memory area with ASCII code 48 characters is not customary, |
| 13 |
possibly integer zeroes were intended instead. |
| 14 |
The check offers a replacement of ``'0'`` with ``0``. Memsetting character |
| 15 |
pointers with ``'0'`` is allowed. |
| 16 |
|
| 17 |
**Case 2: Fill value is truncated** |
| 18 |
|
| 19 |
Memset converts ``fill_value`` to ``unsigned char`` before using it. If |
| 20 |
``fill_value`` is out of unsigned character range, it gets truncated |
| 21 |
and memory will not contain the desired pattern. |
| 22 |
|
| 23 |
**Case 3: Byte count is zero** |
| 24 |
|
| 25 |
Calling memset with a literal zero in its ``byte_count`` argument is likely |
| 26 |
to be unintended and swapped with ``fill_value``. The check offers to swap |
| 27 |
these two arguments. |
| 28 |
|
| 29 |
Corresponding cpplint.py check name: ``runtime/memset``. |
| 30 |
|
| 31 |
|
| 32 |
Examples: |
| 33 |
|
| 34 |
.. code-block:: c++ |
| 35 |
|
| 36 |
void foo() { |
| 37 |
int i[5] = {1, 2, 3, 4, 5}; |
| 38 |
int *ip = i; |
| 39 |
char c = '1'; |
| 40 |
char *cp = &c; |
| 41 |
int v = 0; |
| 42 |
|
| 43 |
// Case 1 |
| 44 |
memset(ip, '0', 1); // suspicious |
| 45 |
memset(cp, '0', 1); // OK |
| 46 |
|
| 47 |
// Case 2 |
| 48 |
memset(ip, 0xabcd, 1); // fill value gets truncated |
| 49 |
memset(ip, 0x00, 1); // OK |
| 50 |
|
| 51 |
// Case 3 |
| 52 |
memset(ip, sizeof(int), v); // zero length, potentially swapped |
| 53 |
memset(ip, 0, 1); // OK |
| 54 |
} |