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