About the member function of string substr

Source: Internet
Author: User

When parsing a string that receives a serial port in LKSNAPSHOT.cpp, there is a sentence:

string cmd = Msg.substr (Cmdstr.length () +1,cmdstr.length ()-cmdstr.length ()-1);

Suspect substr parameter is wrong, and then find the relevant information, found that when the length is greater than the length of the string or less than 0 o'clock, its default to the end of the string, so that the line statement can work correctly.

The specific statements are as follows:

The prototype of this function is substr (size_type off,size_type count)

The first parameter represents the offset in a char array of string, and count is the length of the string starting at the position of the offset.

Incorrect use of these two parameters will cause the program to crash or get the wrong result.

The main two error conditions, off is greater than the length of the array or less than 0, and count is greater than the length of the string or count is less than 0

For the off error, when its greater than the length of the array is the array out of bounds error, the program crash.
When the supplied off is less than 0 o'clock, because the parameter type is unsigned int, it will be coerced, and off becomes a large integer, resulting in an out-of-bounds error, and the program crash.

For count errors, when Count + off is greater than the length of the array, substr internally determines whether it exceeds the length of the array, and if it exceeds it, it will be treated as the maximum subscript of the array. Thus it equates to substr (Off,string.size ()-off);

Similarly, when count is less than 0 o'clock, it is converted to a large integer, and the result is equivalent to substr (Off,string.size ()-off);

In summary, when using this function, be sure to pay attention to the parameters passed in to prevent the program crash, or get the wrong result.

About the member function of string substr

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.