std::memcpy(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::memcpy πŸ’–

okay bestie, this one is from the C++ Standard Libary manual (yes, that's the manual name β€” spelling and all, we're keeping it πŸ’…), and it's literally the β€œcopy bytes” icon. let's get into it ✨


πŸ’– NAME πŸ’–

std::memcpy β€” std::memcpy

that's it. that's the name. she's self-titled, main character energy πŸ‘‘.


✨ Synopsis ✨

Defined in header <cstring> β€” write that down, bestie 🫢

void* memcpy( void* dest, const void* src, std::size_t count );

so here's the tea: it copies count bytes from the object pointed to by src to the object pointed to by dest. both objects are reinterpreted as arrays of unsigned char. that's the whole job πŸ’…

if the objects overlap, the behavior is undefined. not β€œkinda weird”, not β€œmaybe fine” β€” undefined, periodt πŸ’€
if either dest or src is an invalid or null pointer, the behavior is undefined, even if count is zero. yeah, even zero. do not test her 😭
if the objects are potentially-overlapping or not TriviallyCopyable, the behavior of memcpy is not specified and may be undefined. this is not a vibe, this is a warning 🌈

πŸ¦‹ Parameters πŸ¦‹

  • dest β€” pointer to the memory location to copy to
  • src β€” pointer to the memory location to copy from
  • count β€” number of bytes to copy

πŸŽ€ Return value πŸŽ€

dest.

that's it. the same pointer you handed in, boo. she gives it right back 🫢


🌸 Notes 🌸

  • std::memcpy may be used to implicitly create objects in the destination buffer. iconic behavior, honestly ✨
  • std::memcpy is meant to be the fastest library routine for memory-to-memory copy. it is usually more efficient than std::strcpy, which must scan the data it copies or std::memmove, which must take precautions to handle overlapping inputs. the way that speed is the whole point πŸ”₯
  • several C++ compilers transform suitable memory-copying loops to std::memcpy calls. compiler said β€œI got you” fr fr πŸ’…
  • where strict aliasing prohibits examining the same memory as values of two different types, std::memcpy may be used to convert the values. loophole? no bestie, it's literally the sanctioned move 🧚

πŸ“ Example πŸ“

// Run this code

        #include <cstdint>
        #include <cstring>
        #include <iostream>

        int main()
        {
            // simple usage
            char source[] = "once upon a daydream...", dest[4];
            std::memcpy(dest, source, sizeof dest);
            std::cout << "dest[4] = {";
            for (int n{}; char c : dest)
                std::cout << (n++ ? ", " : "") << '\'' << c << "'";
            std::cout << "};\n";

            // reinterpreting
            double d = 0.1;
        //  std::int64_t n = *reinterpret_cast<std::int64_t*>(&d); // aliasing
       violation
            std::int64_t n;
            std::memcpy(&n, &d, sizeof d); // OK

            std::cout << std::hexfloat << d << " is " << std::hex << n
                      << " as a std::int64_t\n" << std::dec;

            // object creation in destination buffer
            struct S
            {
                int x{42};
                void print() const { std::cout << '{' << x << "}\n"; }
            } s;
            alignas(S) char buf[sizeof(S)];
            S* ps = new (buf) S; // placement new
            std::memcpy(ps, &s, sizeof s);
            ps->print();
        }

πŸ“ Output: πŸ“

        dest[4] = {'o', 'n', 'c', 'e'};
        0x1.999999999999ap-4 is 3fb999999999999a as a std::int64_t
        {42}

πŸ‘‘ See also πŸ‘‘

  • memmove β€” moves one buffer to another (function)
  • memset β€” fills a buffer with a character (function)
  • wmemcpy β€” copies a certain amount of wide characters between two non-overlapping arrays (function)
  • copy β€” copies characters (public member function of std::basic_string<CharT,Traits,Allocator>)
  • copy β€” copies a range of elements to a new location (function template)
  • copy_if β€” (function template) (C++11) (the See also section is a little squished in the original, so this is literally what's there, bestie πŸ™ˆ)
  • copy_backward β€” copies a range of elements in backwards order (function template)
  • is_trivially_copyable (C++11) β€” checks if a type is trivially copyable (class template)
  • C documentation for memcpy

okay that's the whole page, bestie. this masterpiece came from http://cppreference.com, dated 2024.06.10, and it's the std::memcpy(3) manual page. go copy some bytes responsibly, mwah πŸ’‹πŸ’–βœ¨

πŸ“¦ where this page comes from