xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/undefined-memory-manipulation.rst (revision 5eaa5312e7943e23155da4f0fbf07b55a200fc60)
1.. title:: clang-tidy - bugprone-undefined-memory-manipulation
2
3bugprone-undefined-memory-manipulation
4======================================
5
6Finds calls of memory manipulation functions ``memset()``, ``memcpy()`` and
7``memmove()`` on non-TriviallyCopyable objects resulting in undefined behavior.
8
9Using memory manipulation functions on non-TriviallyCopyable objects can lead
10to a range of subtle and challenging issues in C++ code. The most immediate
11concern is the potential for undefined behavior, where the state of the object
12may become corrupted or invalid. This can manifest as crashes, data corruption,
13or unexpected behavior at runtime, making it challenging to identify and
14diagnose the root cause. Additionally, misuse of memory manipulation functions
15can bypass essential object-specific operations, such as constructors and
16destructors, leading to resource leaks or improper initialization.
17
18For example, when using ``memcpy`` to copy ``std::string``, pointer data is
19being copied, and it can result in a double free issue.
20
21.. code-block:: c++
22
23  #include <cstring>
24  #include <string>
25
26  int main() {
27      std::string source = "Hello";
28      std::string destination;
29
30      std::memcpy(&destination, &source, sizeof(std::string));
31
32      // Undefined behavior may occur here, during std::string destructor call.
33      return 0;
34  }
35