I am a beginner, and I am learning how to copy a string in C now.
Here is a problem I just met:
Every time I try to use "strcpy" command to copy from string 1 to string 2, Visual Studio 2013 will give me an error/warning message saying that "strcpy" is unsafe and suggest me to use strcpy_s instead.
Can you please explain why is strcpy unsafe to use? And what are the safer alternatives to strcpy?
Here is my code:
#include<stdio.h>
#include<string.h>
main()
{
char str1[] = "Copy a string.";
char str2[15];
char str3[15];
int i;
/* with strcpy() */
strcpy(str2, str1);
/* Without strcpy() */
for (i = 0; str1[i]; i++)
str3[i] = str1[i];
str3[i] = '\0';
/* Display str2 and str3 */
printf("The content of str2: %s\n", str2);
printf("The content of str3: %s\n", str3);
return 0;
}
P.S. I am using Visual Studio 2013 64-bit ultimate on Windows 7 64-bit ultimate. Thank you for your time!
strcpy has no way of knowing how large the destination buffer is (i.e. there is no length parameter) so sloppy programming using it can lead to overrunning the buffer and corrupting other memory. Such an overrun can lead to crashes, odd behaviour and may be exploitable by malware authors.
BTW, look at strncpy that takes a length parameter. One problem to be aware of is that strncpy will not terminate the string if the buffer is too small so it is dangerous in its own way.
In answer to your comment/question - it will depend on context. If you know the buffer is large enough (for example, you allocated it in the previous line at the correct size), use strcpy. If there is any possibility of an overflow then use strncpy and make sure you set the last position in the buffer to null. Note that "any possibility" should be interpreted very generously - unless the previous five or six lines are enough to show safety then use strncpy.
Also see Andon's comment above about strncpy_s. Finally, if you do use strcpy, you might want to add a #pragma to suppress the warning at that location.