When to use strncpy or memmove?

You should never use strncpy (unless you are dealing with that rare specific situation it was introduced for). The function is not intended to be used with zero-terminated C-strings. The name given to that function is just a historical blunder, and happens to be the main source of the confusion for the people who attempt to use it. strncpy is a function introduced to support so-called "fixed width" strings, not zero-terminated strings. Using strncpy with zero-terminated strings is bad programming practice, even though you can whip it into some resemblance of "working" for that purpose.

A function for limited length "safe" string copying does not exist in C library, however some implementations provide it under the name strlcpy, which already became a de-facto standard name for this function. If your implementation does not provide strlcpy, implement it yourself.

Also, it is true that in many cases you can replace str... function with mem... functions, i.e. when you know the exact number of characters to copy.


strncpy() is used to copy data from a source to a dest of a set size, copying (padding) 0x00s if a 0x00 byte is found in the source array (string) before the end of the buffer. As opposed to strcpy which will blissfully copy forever until a 0 byte is found - even if said byte is well beyond your buffer.

memcpy() is used to copy from source to dest no matter what the source data contains. It also tends to be very hardware optimized and will often read system words (ints/longs) at a time to speed up copying when alignment allows.

memmove() is used to copy from an overlapping source and destination area (say moving an array's contents around within itself or something similiar - hence the move mnemonic). It uses strategies (such as possibly copying data starting at the back instead of the front) to protect against problems caused by overlapping regions. It also may be slightly less efficient as there usually isn't much hardware help copying data from back to front.

bcopy() and its relatives (bzero, and a few others) is a byte copy function I've seen now and then in embedded land. Usually, it copies data one byte at a time from source to destination to prevent misaligned memory address issues, though any good memcpy will handle this so its use is quite often suspect.

Good luck!

Tags:

C

String