Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 4 of 4

Thread: Strange looking limit checks in Teensy3 Version of Stream.cpp

  1. #1
    Junior Member
    Join Date
    Jan 2017
    Posts
    17

    Strange looking limit checks in Teensy3 Version of Stream.cpp

    Hello,

    when looking around how Serial is implemented, I stopped at this piece of code in Stream.cpp

    Code:
    String Stream::readString(size_t max)
    {
    	String str;
    	size_t length = str.length();
    	while (length < max) {
    		int c = timedRead();
    		if (c < 0) {
    			setReadError();
    			break;	// timeout
    		}
    		if (c == 0) break;
    		str += (char)c;
    	}
    	return str;
    }
    If I understand the Arduino reference right then str.length() returns the actual size of the String, which is 0 after initialisation. After that the value of length is not more modified in the loop. So the condition is always while(0 < max).

    Do I miss something that is happening in background or is this a bug ?

    The same is happening in readStringUntil, too.

  2. #2
    Senior Member+ MichaelMeissner's Avatar
    Join Date
    Nov 2012
    Location
    Ayer Massachussetts
    Posts
    3,887
    Quote Originally Posted by Frank2 View Post
    If I understand the Arduino reference right then str.length() returns the actual size of the String, which is 0 after initialisation. After that the value of length is not more modified in the loop. So the condition is always while(0 < max).

    Do I miss something that is happening in background or is this a bug ?

    The same is happening in readStringUntil, too.
    I haven't looked at the code. However, I would suspect that this line, which adds a single line to the end of the string bumps up the length:
    Code:
    		str += (char)c;

  3. #3
    Junior Member
    Join Date
    Jan 2017
    Posts
    17
    Thanks for your answer,

    yes that's exactly what I mean. The String object and its internal length ist growing in this line. But the variable with name "length" isn't, because it's nowhere changed in the loop.

    I think
    Code:
    while (str.length() < max) {
    is what is realy meant there.

    But anyway tho code is Arduino compatible as it is, because the original Arduino libraries don't do any length checks there. So introducing a limit may break some people's code. The only problem is, that not having a limit may cause other trouble.

  4. #4
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    23,066
    Yes, I believe you're right. The length check is probably ineffective. A low priority bug which should get tested and fixed if the tests confirm the problem...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •