itsanjan / arduino

Automatically exported from code.google.com/p/arduino
Other
0 stars 0 forks source link

IDE 22 string::substring bug #602

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago

The substring code of the String class has a bug. It checks if the right 
parameter is larger than its inner length to prevent out of bound error, which 
is good!
- if ( right > _length ) - 

However the code does not check the left parameter,
==> that means left can become larger than right, thereby corrupting the output 
in the line -  String outPut = ( _buffer + left ); -

String::substring( unsigned int left, unsigned int right ) const
{
  if ( left > right )
  {
    int temp = right;
    right = left;
    left = temp;
  }

  if ( right > _length )
  {
    right = _length;
  } 

  // ADDED 4 LINES
  if ( left > _length ) 
  {
    left = _length;
  } 

  char temp = _buffer[ right ];  // save the replaced character
  _buffer[ right ] = '\0';  
  String outPut = ( _buffer + left );  // pointer arithmetic
  _buffer[ right ] = temp;  //restore character
  return outPut;
}

The bug can be reproduced by taking a string with length 3 and ask the 
substring( 5,6); in which both parameters are larger than the string length.

Found during discussion in this thread
- http://arduino.cc/forum/index.php/topic,70603.0.html -

Regards,
Rob

Original issue reported on code.google.com by rob.till...@gmail.com on 28 Aug 2011 at 11:41

GoogleCodeExporter commented 9 years ago
It looks like this has been fixed as part of the string rewrite coming in 
Arduino 1.0: 
https://github.com/arduino/Arduino/blob/new-extension/hardware/arduino/cores/ard
uino/WString.cpp

You can download and try a beta version here: 
http://code.google.com/p/arduino/wiki/Arduino1

If this is still broken in 1.0, please let me know.

Original comment by dmel...@gmail.com on 28 Aug 2011 at 6:11