11 ms·
Can someone explain to me what's wrong with memcpy?
by junippor 6y ago
Can someone explain to me what's wrong with memcpy?
- scoutt 6y agoI think the most destructive thing is that you can overflow the destination buffer. With memcpy_s you have to specify the destination buffer size so you can (supposedly) prevent it.
- junippor 6y agoOk fine. As far as footguns go, that's not the most subtle one.
- fanf2 6y agoIt can do the wrong thing if the source and destination overlap. Use memmove() instead.
- longcommonname 6y agoIn addition to the others answers, memcpy of size zero is undefined in certain cases. This and the other two bugs can be particularly nasty when doing something such as an arena allocator or any other means of user memory pools. After an incredibly long slog on some particularly nasty corruption issues years ago I was only able to identify the problem by using ld preload and patching memcpy with some simple value and boundary checks for these three problems. Each of them was a source of the corruption.
- rurban 6y agoMany things. Besides the already explained buffer overflow, overlap and zero size UB, compiler also frequently chose to ignore it. The secure variant will fill the dest buffer regardless if the compiler thinks this is a useless side effect. Similar to the memset_s security problems nobody cares to fix.