Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

c - Trying to use the strcpy_s in vsc?

When I try to run the code i get:

warning: implicit declaration of function 'strcpy_s' [-Wimplicit-function-declaration]

I included string.h and stdio.h.

Code:

#include <string.h>
#include <stdio.h>

int main(void) {
    static int foo = 0;
    char s[12];
    char *t = "01234567890123"
    printf("foo %p
 s %p
", &foo, s);
    strcpy_s(s, 11, t);
}
question from:https://stackoverflow.com/questions/65889778/trying-to-use-the-strcpy-s-in-vsc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)] = '' ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...