6 ms·
Real men use memcpy
by coding123 2y ago
Real men use memcpy
- mjevans 2y agoIf you know the length (and that it fits) mempcpy() , then add the terminator yourself to be sure. memcpy has the slightly annoying flaw of returning a copy of the dest argument (already known data) rather than the more useful new information of a pointer to the end of the set memory. #IFNDEF _GNU_SOURCE #DEFINE mempcpy(X, Y, Z) (void *)((memcpy(X, Y, Z) - 1) + Z) #ENDIF // Not quite the same but close enough mempcpy, fails for Z = 0 edited: Since X shouldn't be NULL and thus not 0, apply the subtraction first to avoid the corner case (which also shouldn't happen given common HW / OS regions) of X + Z > (~(size_t)0) (SIZE_MAX)
- mjevans 2y agoI remembered the return value incorrectly. It's even better in that it returns a pointer to the byte immediately AFTER the last written. So remove the - 1. PS: there's also a version which works with wchar_t types (be it 2, 4 or whatever else) #DEFINE mempcpy(X, Y, Z) (void *)(memcpy(X, Y, Z) + Z) #DEFINE wmempcpy(X, Y, Z) (void *)(memcpy(X, Y, Z * sizeof(wchar_t)) + Z * sizeof(wchar_t))