25

what should I use when I want to copy src_str to dst_arr and why?

char dst_arr[10];
char *src_str = "hello";

PS: my head is spinning faster than the disk of my computer after reading a lot of things on how good or bad is strncpy and strlcpy.

Note: I know strlcpy is not available everywhere. That is not the concern here.

Raffi Khatchadourian
  • 3,042
  • 3
  • 31
  • 37
hari
  • 9,439
  • 27
  • 76
  • 110

6 Answers6

38

strncpy is never the right answer when your destination string is zero-terminated. strncpy is a function intended to be used with non-terminated fixed-width strings. More precisely, its purpose is to convert a zero-terminated string to a non-terminated fixed-width string (by copying). In other words, strncpy is not meaningfully applicable here.

The real choice you have here is between strlcpy and plain strcpy.

When you want to perform "safe" (i.e. potentially truncated) copying to dst_arr, the proper function to use is strlcpy.

As for dst_ptr... There's no such thing as "copy to dst_ptr". You can copy to memory pointed by dst_ptr, but first you have to make sure it points somewhere and allocate that memory. There are many different ways to do it.

For example, you can just make dst_ptr to point to dst_arr, in which case the answer is the same as in the previous case - strlcpy.

Or you can allocate the memory using malloc. If the amount of memory you allocated is guaranteed to be enough for the string (i.e. at least strlen(src_str) + 1 bytes is allocated), then you can use the plain strcpy or even memcpy to copy the string. There's no need and no reason to use strlcpy in this case , although some people might prefer using it, since it somehow gives them the feeling of extra safety.

If you intentionally allocate less memory (i.e. you want your string to get truncated), then strlcpy becomes the right function to use.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 1
    Thanks. When you say "strncpy is never the right answer when you are working with zero-terminated strings", you mean the source string or dest? – hari Aug 08 '11 at 19:47
  • 2
    @hari: The destination string. `strncpy` is a *conversion* function, which converts zero-terminated source string to a non-terminated fixed-width target string. – AnT stands with Russia Aug 08 '11 at 21:01
  • So, If my destination string is `char dst_arr[10];` that is not null-terminated. Then I should use `strlcpy` correct? – hari Aug 08 '11 at 22:33
  • 2
    @hari: Er... I don't understand the question. It doesn't matter what your `dst_arr` is originally. Originally it is just a block of raw uninitialized memory. The question is what you want do create in that `dst_arr`. I assumed that you want to create a standard ordinary zero-terminated string in `dst_arr` (since you said that you wanted to *copy* an ordinary zero-terminated string to it). If so, use `strlcpy`. If instead you want to create a "fixed-width string" in `dst_arr` (which is rather unusual, since most of the time nobody ever uses fixed-width strings these days), use `strncpy`. – AnT stands with Russia Aug 08 '11 at 22:57
  • My bad. I do want standard ordinary zero-terminated string. Thanks much for your help. – hari Aug 08 '11 at 23:04
  • 1
    I'd add that `strncpy` doesn't require the source string to be null-terminated. If it doesn't find a nul in n chars, it stops looking. But it treats a nul as a termination if it finds it in the first n chars. unlike `strlcpy`, which always needs to find the nul at the end of `s`, so that it can return `strlen(s)`. – greggo Nov 03 '15 at 15:44
  • strlcpy truncation is not safe, it's a security risk. safe would be the safe C11 variant strcpy_s(). – rurban Nov 16 '17 at 00:42
7

strlcpy() is safer than strncpy() so you might as well use it.
Systems that don't have it will often have a s_strncpy() that does the same thing.

Note : you can't copy anything to dst_ptr until it points to something

Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
  • 2
    It is a bit safer, but also not safe. E.g. strlcpy truncates the source string to fit in the destination, which is a security risk. – rurban Nov 16 '17 at 00:40
4

I did not know of strlcpy. I just found here that:

The strlcpy() and strlcat() functions copy and concatenate strings respectively. They are designed to be safer, more consistent, and less error prone replacements for strncpy(3) and strncat(3).

So strlcpy seams safer.

Edit: A full discussion is available here.

Edit2:

I realize that what I wrote above does not answer the "in your case" part of your question. If you understand the limitations of strncpy, I guess you can use it and write good code around it to avoid its pitfalls; but if your are not sure about your understanding of its limits, use strlcpy.

My understanding of the limitations of strncpy and strlcpy is that you can do something very bad with strncpy (buffer overflow), and the worst you can do with strlcpy is to loose one char in the process.

jfg956
  • 16,077
  • 4
  • 26
  • 34
  • Thanks for explanation. How can I loose one char in `strlcpy`? can you please explain? – hari Aug 08 '11 at 19:40
  • If you use strncpy to copy a string larger than your buffer, it will not put a `'\0'` at the end of the buffer. If you use strlcpy, the `'\0'` will be there, but one less char will be in your buffer. So if someone used strncpy when he should have used memcpy, using strlcpy instead of strncpy will loose him a char. – jfg956 Aug 08 '11 at 19:50
  • Thanks. So when using `strlcpy` only thing you need to take care is, you should provide destination with (src_length + 1 for null). Correct? – hari Aug 08 '11 at 20:00
  • Not exactly. The very important thing is to give at most dst size in the 3rd argument to avoid buffer overflow. From there, if this 3rd argument is at least `src_length + 1`, no char will be lost in the copy. Maybe you want the src to be truncated, and this will be happening if the 3rd argument is less than `src_length + 1`. But be careful, to truncate str to 5 chars, the 3rd argument should be 6, and dst size must be at least 6 to avoid buffer overflow. – jfg956 Aug 08 '11 at 20:30
  • Truncation is not really important to me. What I Want to make sure is, it should fully copy with a NULL at the end. To make sure this, should I provide `src_length + 1` all the time? (just to be sure?) – hari Aug 08 '11 at 20:35
  • Yes, to copy a string of `len` chars (`"hello"` is of size 5), you need a buffer of `len+1` chars. – jfg956 Aug 08 '11 at 20:37
  • 4
    @hari No, that is wrong. The point of `strlcpy` is to avoid overflow of the output buffer. That means that the `size` argument is the size of the **destination** buffer, not the source buffer ... precisely, it is the amount of space remaining in the destination buffer. If you "provide src_length + 1 all the time", your code will be riddled with buffer overflow bugs. – Jim Balter Aug 09 '11 at 00:17
  • Jim Balter: got that. I realized that from @AndreyT 's response. Thanks anyways. Appreciate your inputs. – hari Aug 09 '11 at 00:29
1

You should always the standard function, which in this case is the C11 strcpy_s() function. Not strncpy(), as this is unsafe not guaranteeing zero termination. And not the OpenBSD-only strlcpy(), as it is also unsafe, and OpenBSD always comes up with it's own inventions, which usually don't make it into any standard.

See http://en.cppreference.com/w/c/string/byte/strcpy

The function strcpy_s is similar to the BSD function strlcpy, except that strlcpy truncates the source string to fit in the destination (which is a security risk)

  • strlcpy does not perform all the runtime checks that strcpy_s does
  • strlcpy does not make failures obvious by setting the destination to a null string or calling a handler if the call fails.
  • Although strcpy_s prohibits truncation due to potential security risks, it's possible to truncate a string using bounds-checked strncpy_s instead.

If your C library doesn't have strcpy_s, use the safec lib. https://rurban.github.io/safeclib/doc/safec-3.1/df/d8e/strcpy__s_8c.html

rurban
  • 4,025
  • 24
  • 27
-1

First of all, your dst_ptr has no space allocated and you haven't set it to point at the others, so assigning anything to that would probably cause a segmentation fault.

Strncpy should work perfectly fine - just do:

strncpy(dst_arr, src_str, sizeof(dst_arr));

and you know you wont overflow dst_arr. If you use a bigger src_str you might have to put your own null-terminator at the end of dst_arr, but in this case your source is < your dest, so it will be padded with nulls anyway.

This works everywhere and its safe, so I wouldn't look at anything else unless its intellectual curiousity.

Also note that it would be good to use a non-magic number for the 10 so you know the size of that matches the size of the strncpy :)

John Humphreys
  • 37,047
  • 37
  • 155
  • 255
  • `strncpy` is almost never the right thing, as it zero-fills but does not zero-terminate. The OP wants `strlcpy`, which zero-terminates and does not zero-fill. Also, it is a mistake to talk about "in this case", because the question of course just an illustration ... real code is not going to be copying a fixed string like "hello" to a fixed sized buffer known to be bigger. – Jim Balter Aug 09 '11 at 00:19
-1

you should not use strncpy and not strlcpy for this. Better you use

*dst_arr=0; strncat(dst_arr,src_arr,(sizeof dst_arr)-1);

or without an initialization

sprintf(dst_arr,"%.*s",(sizeof dst_arr)-1,src_arr);

dst_arr here must be an array NOT a pointer.

user411313
  • 3,930
  • 19
  • 16