Procedure Strings.Replace has a bug

Procedure Strings.Replace has a bug

Postby manumart1 » Fri Mar 21, 2014 11:23 am

According to specification:
PROCEDURE Replace (VAR s: ARRAY OF CHAR; pos, len: INTEGER; IN rep: ARRAY OF CHAR)
Replaces the stretch [pos, MIN(pos+len, Len(s))) in s with the string in rep. The characters after the replaced stretch are moved if necessary. The result is truncated if s is not large enough.
Hint: if len = 0 then rep is inserted in s at position pos. If LEN(rep$) = 0 then the stretch [pos, MIN(pos+len, LEN(s$))) is deleted from s.

Pre
len >= 0 20
pos >= 0 21
Valid(s) & Valid(rep) (not checked)

Post
Valid(s)

But sometimes in the string s the final char 0X (which signals the end) is lost, and the postcondition (not explicitly checked) does not hold. The bug is detected afterwards, for example when trying to print the resulted string. For example:
Code: Select all
VAR a: ARRAY 5 OF CHAR;
ERROR 1:
    a := "ABCD";
    Strings.Replace(a, 1, 1, "xy");
    StdLog.String(a); <-- index out of range
ERROR 2:
    a := "ABCD";
    Strings.Replace(a, 1, 0, "x");
    StdLog.String(a); <-- index out of range

I tried to rewrite Strings.Replace from scratch, but is very difficult. Fortunately I think I have found a possible fix:
Code: Select all
PROCEDURE Replace* (VAR s: ARRAY OF CHAR; pos, len: INTEGER; IN rep: ARRAY OF CHAR);
...
        ELSE (* insert the remaining part of rep *)
            len := LEN(rep$) - j; k := lenS + len;
            IF k > max THEN k := max END;
            s[k] := 0X; DEC(k); <--- DEC(k) is added
            WHILE k - len >= i DO s[k] := s[k-len]; DEC(k) END;
            WHILE (rep[j] # 0X) & (i < max) DO s[i] := rep[j]; INC(i); INC(j) END
        END
    END
END Replace;

I am using BB CPC Edition 12.12.2013
Regards
manumart1
 
Posts: 61
Joined: Tue Sep 17, 2013 6:25 am

Re: Procedure Strings.Replace has a bug

Postby Ivan Denisov » Fri Mar 21, 2014 6:25 pm

Hello Manuel,

I agree with you. Neither the specification nor the intention of the source code corresponds to this behaviour. And I think that your correction is good too.

It's strange to think that this bug was never noticed before in a so often used procedure!

Regards.

Gérard
User avatar
Ivan Denisov
 
Posts: 227
Joined: Tue Sep 17, 2013 12:21 am
Location: Krasnoyarsk, Russia

Re: Procedure Strings.Replace has a bug

Postby manumart1 » Sat Jan 30, 2016 6:13 pm

Solved in February 2015, issue-#28, see http://forum.blackboxframework.org/viewtopic.php?f=49&t=189
manumart1
 
Posts: 61
Joined: Tue Sep 17, 2013 6:25 am


Return to Bug

Who is online

Users browsing this forum: No registered users and 1 guest

cron