3 ms·
> except for plain data types where copying is literally memcpy what do you mean by this? If I say `let x = 5; let y = x;` in rust, that's a "plain data type c
by xdavidliu 4y ago
> except for plain data types where copying is literally memcpy
what do you mean by this? If I say `let x = 5; let y = x;` in rust, that's a "plain data type copy" of a stack value, but memcpy is usually used to copy heap memory. What connection between copying of primitive simple stack values and memcpy are you suggesting here?
- orra 4y ago> What connection between copying of primitive simple stack values and memcpy are you suggesting here? They're just using 'memcpy' as a shorthand for saying the bitpattern is blitted. Semantically, that's like a memcpy. The point is, there are no expensive allocations, nor do any embedded pointer fields need adjusted, etc.
- kccqzy 4y agoThe compiler can optimize memcpy with a known size into a small number of move instructions so they are identical to copying stack values. Try playing with memcpy on Godbolt and you'll find that the compiler will compile the memcpy to a single mov instruction when the size is small, and some movdqu/movups when the size is slightly large, and only a function call when the size is huge. > memcpy is usually used to copy heap memory memcpy is often used in low-level serialization / deserialization code since you can't just cast a buffer pointer to a uint32_t pointer and dereference that; the solution is memcpy between variables that are often both on the stack.
- chlorion 4y agoWhy do you think memcpy is normally used to copy heap memory? It's just a general bitwise copy from one location to the other. I think the confusion here is that there isn't always a literal call to memcpy for copying small types like ints in the emitted code, but it's always doing something with the same effect and maybe sometimes using an actual memcpy (probably when copying arrays?). Also something interesting is that memcpy is used for copying data between stack variables in C sometimes when you need to convert some type to another one without using a cast.