When we use strcpy (), if there is space space considered when the source string is greater than the target string is what happens: The following I made a simple case:
#include <stdio.h> #include <string.h> int main() { char *obj="Hello World!"; char dest[5]={0}; strcpy(dest,obj); printf("%s\n",dest); return 0; }
When using gcc compiler implementation, there have been mistakes which is obviously very dangerous, so libc there a more cautious string copy function strncpy (), continue to make a case:
#include <stdio.h> #include <string.h> int main() { char *obj="Hello World!"; char dest[5]={0}; strncpy(dest,obj,sizeof(dest)-1); printf("%s\n",dest); return 0; }
After compiling the results of the implementation of the output is: hell did not appear the mistakes, so when the need to use the string copy when the priority use strncpy () is a more good choice There is a need to pay attention to detail, we need to leave. a space to store the units '\ 0', so in the third argument I use sizeof (dest) -1, where if you do not -1, the segment still an error, because the string is \ 0 marks the end , so be sure to leave a space.