Is strncpy() a specialization of memcpy()?

后端 未结 5 1628
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 01:59

Just curious to know (as we use these functions often). I don\'t see any practical difference between strncpy() and memcpy(). Isn\'t it worth to say that effectively,

         


        
5条回答
  •  忘掉有多难
    2021-01-25 02:16

    There is a difference, see this part of the strncpy page you linked to (emphasis mine):

    Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

    So if the string to be copied is shorter than the limit, strncpy pads with zero while memcpy reads beyond the limit (possibly invoking undefined behaviour).

提交回复
热议问题