I recently stumbled across an article that claims Microsoft is banning the memcpy() function in its secure programming shops. I understand the vulnerabilities inherent in the function, but is it necessary to ban its use entirely?
Should programs I write be avoiding memcpy() entirely, or just ensuring that it’s used safely? What alternatives exist that provide similar but safer functionalilty?
Microsoft provides alternatives to memcpy and wmemcpy that validate their parameters.
memcpy_s says, “Hmm, before I read from this address, let me verify for myself that it is not a null pointer; and before I write to this address, I shall perform that test again. I shall also compare the number of bytes I have been requested to copy to the claimed size of the destination; if and only if the call passes all these tests shall I perform the copy.”
memcpy says “Stuff the destination into a register, stuff the source into a register, stuff the count into a register, perform MOVSB or MOVSW.” (Example on geocities, not long for this world: http://www.geocities.com/siliconvalley/park/3230/x86asm/asml1013.html)
Edit: For an example in the wild of the Your Wish Is My Command approach to memcpy, consider OpenSolaris, where memcpy is (for some configurations) defined in terms of bcopy, and bcopy (for some configurations) is …
Edit: Thanks, Millie Smith! Here is what was on the geocities page I linked above:
MOVS
The instruction movs is used to copy source string into the destination (yes, copy, not move). This instruction has two variants: movsb and movsw. The movsb (“move string byte”) moves one byte at a time, whereas movsw moves two bytes at a time.
Since we’d like to move several bytes at a time, these movs instructions are done in batches using rep prefix. The number of movements is specified by CX register. See the example below:
This example will copy 100 bytes from src to dest. If you replace movsb with movsw, you copy 200 bytes instead. If you remove the rep prefix, the CX register will have no effect. You will move one byte (if it is movsb, or 2 bytes if it is movsw).