Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

c - When to use strncpy or memmove?

(gcc 4.4.4 c89)

I have always used strncpy to copy strings. I have never really used memmove or memcpy very much. However, I am just wondering when would you decide whether to use strncpy, memmove, or memcpy?

The code I am writing is for a client/server application. In the documentation they use bcopy. However, could I do the same with the others?

bcopy((char*)server->h_addr,
      (char*)&serv_addr.sin_addr.s_addr,
      server->h_length);

Many thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...