strncpy documentation question

后端 未结 6 1628
傲寒
傲寒 2020-12-10 07:47

At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:

No null-char

6条回答
  •  醉话见心
    2020-12-10 08:24

    The string "foo" has 3 characters + 1 null-terminator (it's stored as "foo\0") giving a total length of 4. If you call strncpy with n=3 (or fewer) it won't append a null-terminator to the end of the target string, but will copy only "foo". Attempting to print the resulting string will result in undefined behaviour due to the lack of a null-terminator which signals the end of the string.

    You have to be very careful of this and either pass n one greater than the maximum source or add the null-terminator yourself.

提交回复
热议问题