Ratio of strcpy_s to strcpy

Source: Internet
Author: User

The functions of strcpy_s and strcpy () functions are almost the same. The strcpy function, just like the gets function, has no way to ensure a valid buffer size, so it can only assume that the buffer is large enough to accommodate the string to be copied. During program execution, this will lead to unpredictable behavior. Use strcpy_s These unpredictable behaviors can be avoided.
This function can use both the number of buffers and the number of three buffers to ensure the buffer size.
When there are three shards:
Errno_t strcpy_s (
Char * strdestination,
Size_t numberofelements,
Const char * strsource
);
When there are two shards:
Errno_t strcpy_s (
Char (& strdestination) [size],
Const char * strsource
); // C ++ only

Example:
# 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 shards Strcpy_s (STR, "hello ");//The number of two partitions is assumed to be char * STR = new char [7]. An error occurs: The system prompts that two partitions are not supported. 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 "); // strcpy_s (STR, "hello"); // it is assumed that char * STR = new char [7]; an error occurs: the message "cout <" strlen (str1): "<strlen (str1) <Endl <" strlen (STR): "<strlen (STR) <Endl; printf (str1); printf ("\ n"); cout <STR <Endl ;}
Int main () {test (); Return 0 ;}
Output:
Strlen (str1): 11// Note that strlen (str1) is used to calculate the length of a string and does not contain "\ 0" at the end of the string "!!!
Strlen (STR): 5
Hello World
Hello

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.