Comparison of strcpy_s and strcpy

Source: Internet
Author: User

the strcpy_s and strcpy () functions are almost identical. The strcpy function. Just like the Get function, it has no way to guarantee a valid buffer size, so it can only assume that the buffer is large enough to hold the string to be copied. This leads to unpredictable behavior when the program is executed.

with strcpy_s, To avoid these unpredictable behaviors.
This function can be used with two parameters and three parameters, only to guarantee the buffer size.


Three parameters:
errno_t strcpy_s (
Char *strdestination,
size_t numberofelements,
const char *strsource
);
two parameters:
errno_t strcpy_s (
char (&strdestination) [size],
const char *strsource
); C + + only

Examples:
#include <iostream>#include <cstring>using namespace std;
void Test (void){Char *str1=null;str1=new char[20];Char str[7];strcpy_s (str1,20, "Hello World");//Three referencesstrcpy_s (str, "Hello");// two references but assumes: Char *str=new char[7]; Error: Prompt does not support two parameters cout<< "strlen (str1):" <<strlen (str1) <<endl<< "strlen (str):" <<strlen (str) < <endl;printf (str1);printf ("\ n");cout<<str<<endl;}
int main (){Test ();return 0;}#include <iostream>#include <string.h>using namespace std;
void Test (void) {char *str1=null;str1=new Char[20];char str[7];strcpy_s (str1,20, "Hello World");//three Parameters strcpy_s (str, " Hello ");//Two references but assumes: Char *str=new char[7]; Error: Prompt does not support two parameters cout<<" strlen (str1): "<<strlen (STR1) <<endl << "strlen (str):" <<strlen (str) <<endl;printf (STR1);p rintf ("\ n"); Cout<<str<<endl;}
int main () {Test (); return 0;}
the output is:
strlen ( str1): one///Another note: strlen (str1) is the length of the computed string. does not contain "\" at the end of the string!!!
strlen (str): 5
Hello World
Hello

Comparison of strcpy_s and strcpy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.