strcpy_s()
may not be declared without __STDC_WANT_LIB_EXT1__
:
#define __STDC_WANT_LIB_EXT1__
#include <string.h>
If the implementation does not define __STDC_LIB_EXT1__
then the extension is not available in your library.
Since you are not checking the errno_t
return value from strcpy_s
, you would do better perhaps to use the more broadly supported strncpy()
.
The advantages of strcpy_s()
(or even strncpy_s()
) are that they tell you when the have failed, and on success guarantee the destination is NUL terminated. But since you are not checking for error, there is little advantage. That can be resolved by explicitly ensuring that s[11]
is NUL by for example:
Zero initialisation:
char s[12] = {0} ;
or assignment:
s[sizeof(s) - 1] = '' ;
#include <string.h>
#include <stdio.h>
int main(void)
{
static int foo = 0;
char s[12] = {0} ;
char *t = "01234567890123"
printf("foo %p
s %p
", &foo, s);
strncpy(s, t, sizeof(s) - 1) ) ;
return 0 ;
}
Note that in this case strncpy()
will copy 11 characters to s
, and will not write a NUL terminator. In this case I have zero initialised the entire array, but in cases where destination is not known to be zero initialised or the length variable then a safer idiom is to add the terminator :
strncpy(s, t, len ) ;
s[len] = '' ;
Or specifically in this example:
strncpy(s, t, sizeof(s) - 1) ) ;
s[sizeof(s) - 1)] = '' ;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…