Procedure Strings.Replace has a bug

Post Reply
manumart1
Posts: 67
Joined: Tue Sep 17, 2013 6:25 am

Procedure Strings.Replace has a bug

Post by manumart1 »

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
User avatar
Ivan Denisov
Posts: 362
Joined: Tue Sep 17, 2013 12:21 am
Location: Krasnoyarsk, Russia

Re: Procedure Strings.Replace has a bug

Post by Ivan Denisov »

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
manumart1
Posts: 67
Joined: Tue Sep 17, 2013 6:25 am

Re: Procedure Strings.Replace has a bug

Post by manumart1 »

Solved in February 2015, issue-#28, see http://forum.blackboxframework.org/view ... f=49&t=189
Post Reply