3 ms·
I see they've finally changed the memcpy() specification to forbid overlapping memory areas completely. Previously, it was defined to copy from low addresses t
by david-given 10y ago
I see they've finally changed the memcpy() specification to forbid overlapping memory areas completely.
Previously, it was defined to copy from low addresses to high addresses, which meant you could use this to fill an array:
p[0] = 42;
memcpy(&p[1], &p[0], sizeof(p)-sizeof(*p));
And people did.
- caf 10y agoThe original 1989 ANSI C specification stated, in "4.11.2.1 The memcpy function": If copying takes place between objects that overlap, the behavior is undefined. So it has been this way in C since the first official standard. I don't have a first edition K&R so I can't see what that said, though.
- david-given 10y agoHuh. You're quite right. Well, it may have been undefined, but in practice the behaviour was standardised and couldn't be changed without breaking existing code... which is basically C in a nutshell.
- caf 10y agoCode like your example would have been broken by real standard library implementations very early in the piece, because even a forward-copying implementation that does word-at-a-time copies (a straightforward and obvious optimisation with real and significant benefits on many machines of the era) would have broken it.