JavaProphet
JavaProphet

Reputation: 991

Is it bad practice to use memcpy over strncpy or similar?

When moving strings between buffers, I frequently treat char* as data buffers, and use none of the string buffer (strncpy, strncat, etc). Example:

memcpy(target, src, strlen(src) + 1) // after buffer size checks
//vs
strncpy(target, src, target_size - 1);
target[target_size - 1] = 0;

Is this a bad practice?

EDIT: I know the difference, this is not a duplicate, but rather a question of standard practice.

Upvotes: 2

Views: 7294

Answers (2)

R Sahu
R Sahu

Reputation: 206627

Use of

memcpy(target, src, strlen(src) + 1) // after buffer size checks

potentially involves traversing the string twice -- once in strlen and once in memcpy. You take a small performance hit that you don't if you use strcpy.

If you compute the length of the string for unrelated reasons or have the length of the string from other resources, it's unclear to me whether memcpy is better or worse than strncpy.

If you don't the compute the length of the string for other reasons or don't have the length of the string from other resources, it is better to use strcpy instead of memcpy or strncpy.

Upvotes: 3

Taywee
Taywee

Reputation: 1335

If you know the semantics and sizes, it's not an issue. Remember that strncpy will stop at the first null and also fill the following bytes in the destination up to n characters with null bytes if the string is shorter (it will not write a null byte if there wasn't one in the source). strncpy can also give you a little bit of better typechecking, as it expects a char * in all cases, rather than a void *.

Which is more efficient is up for debate, but based on CPU bulk instructions which can copy an entire block of memory in one instruction, memcpy is probably faster, as strncpy would check each copied byte for a NUL character.

Upvotes: 2

Related Questions