strncpy or strlcpy in my case

前端 未结 6 1295
执笔经年
执笔经年 2020-12-10 11:21

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

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

P

6条回答
  •  生来不讨喜
    2020-12-10 11:39

    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.

提交回复
热议问题