C-style string

Source: Internet
Author: User

Although C ++ supports C-style strings, it is best not to use them in C ++ programs. This is because c-style strings are not easy to use, but also easily cause program vulnerabilities, which is the root cause of many security problems.

The string literal value is an example of a general structure, which is a C-style string inherited by C ++. C-style strings are not a type, but a conventional writing method formed to express and use strings. Strings written in this habit are stored in the character array and ended with an empty string. Ending with an empty character means that an empty character ('\ 0') is followed by the last character of the string '). Generally, pointers are used to operate these strings.

C Standard Library string Function

The following table lists a set of functions provided by the C language standard library. These functions can be used to operate C-style strings. They are defined in the string header file, and the string is the c-Language header file string. c ++ version of H.

C-style string functions

Strlen (p) returns the length of P. null characters are not included.

Strcmp (P1, P2) compares the equality between P1 and P2. If p1 = P2, 0 is returned. If P1> P2, a positive value is returned. If P1 <P2, a negative value is returned.

Strcat (P1, P2) attaches p2 to P1 and returns p1

Strcpy (P1, P2) Copies p2 to P1 and returns p1

The pointer to the input function must point to an array ending with a null character.:

Char Ca [] = {'C', '+', '+'}; // do not end with an empty character

Cout <strlen (CA) <Endl; // serious error: the Ca does not end with a NULL Character

In this example, although CA is also a character array, it does not end with null characters, so the above program will produce undefined results. The strlen function may keep searching forward along the location of the CA in the memory until it encounters null characters.

Comparison string

The methods for comparing two C-style strings are quite different from those for comparing string objects in the standard library. When comparing string objects in the standard library, common Relational operators and equality operators are used:

String S1 = "a string example ";

String S2 = "a different string ";

If (S1 <S2) // false: S2 is smaller than S1

If you use these operators on two C-style strings, the actual comparison will be the pointer rather than the string itself:

Const char CA1 [] = "a string example ";

Const char Ca 2 [] = "a different string ";

If (CA1 <Ca 2) // undefined: try to compare two irrelevant addresses

Keep in mind that when using an array, we actually use a pointer to the first element of the array. Therefore, the above if condition actually compares the values of two const char. The two pointers do not point to the same object, so undefined results are obtained.

To compare two C-style strings, you need to call the strcmp function. In this case, the comparison is no longer a pointer. If the two strings are equal, strcmp returns 0. If the preceding string is large, a positive value is returned. If the following string is large, a negative value is returned:

If (strcmp (cache, ca 2) <0) // compare the two string objects S1 <S2 has the same effect

The size of the target string is specified by the caller.

Similar operations to connect to or copy a C-style string are also very different from those of the string object in the standard library. For example, to connect the two string objects S1 and S2 that have just been defined, you can directly use the form below Ctrip:

// Initialize largestr to S1. A space is connected to S2.

String largestr = S1 + "" + S2;

If the same operation is performed on the arrays 'ec1' and 'ec2', an error will occur. Expression A1 + Ca 2 tries to add the two pointers. Obviously, this operation is meaningless and definitely illegal.

The correct method is to use strcat and strcpy functions. However, to use these two functions, you must also provide an array for storing the result string. The array must be large enough to accommodate the result string and the trailing null characters. Although the following code is common, it is full of security risks and can easily cause serious errors:

// If the size of largestr is calculated incorrectly, a serious error is thrown.

Strcpy (largestr, CA1); // copy the CA1 to largestr

Strcat (largestr, ""); // Add a space at the end of largestr

Strcat (largestr, ca 2); // connect Ca 2 to the end of largestr.

 

Mix string objects and C-style strings

You can use the string literal value to initialize a String object:

String S ("Hello world! "); // The content of S is Hello World

In general, any occurrence of the string literal value can be replaced by an array of characters ending with null characters:

  • You can use an array of characters ending with null characters to initialize a String object or assign a value to a string object.
  • In addition operations on string objects, an array of characters ending with null characters can be used as one of the computing objects (not both calculation objects ): you can use an array of null characters as the right operation object in the compound value assignment of a string object.

In turn, the above properties are not true: if the program requires a C-style string somewhere, it cannot be replaced by a string object directly. For example, a string object cannot be used to initialize a pointer to a character. To complete this function, string provides a member function named c_str:

Char * STR = s; // error: the string object cannot be used to initialize char *

Const char * STR = S. c_str (); // correct

As the name suggests, the return value of the c_str function is a C-style string. That is to say, the returned result of the function is a pointer pointing to an array of characters ending with null characters, and the data stored in this array is exactly the same as that of the string object. The result pointer type is const char *, so that we do not change the content of the character array.

We cannot guarantee that the array returned by the c_str function is always valid. In fact, if the value of S is changed in subsequent operations, it may make the previously returned array useless.

 

Use arrays to initialize a vector object

We have discussed earlier that it is not allowed to use one array to assign an initial value to an array of another built-in type, or to use a vector object to initialize an array. Conversely, you can use an array class to initialize a vector object. To achieve this goal, you only need to specify the first and last element addresses of the region to be copied:

Int int_arr [] = {0, 1, 2, 3, 4, 5 };

// Ivec has six elements, which are copies of corresponding elements in int_arr.

Vector <int> ivec (begin (int_arr), end (int_arr ));

In the above Code, the two pointers used to create ivec actually specify the position of the value to be initialized in the array int_arr. The second pointer should point to the next position of the element at the end of the area to be copied. In this example, the begin and end functions of the standard library are used to calculate the first and last pointers of int_arr respectively. In the final result, ivec contains six elements, their order and values are exactly the same as those of the array int_arr.

 

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.