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!
strncpy
is also unsafe. They want you to usestrncpy_s
, which adds a second parameter indicating size and modifies the standard behavior ofstrncpy
, such that truncated strings append a null-terminator. Needless to say, all of these_s
functions are non-standard and I generally just define a certain pre-processor definition to make that warning go away. – Letterint main(void)
orint main(int argc, char **argv)
– Unhairstrcpy()
is a perfectly safe function (unlike, say,gets()
) in the right hands. Unfortunately, a lot of programmers don't code well, and then demand a "safer" language. Wimps. – Innominatechar str2[sizeofstr1];
and avoid magic numbers like15
. Let the compiler do the work to compute the needed size. – Tedford