Skip to content

Commit

Permalink
Add a fast path for returning "" from repeat(str, 0) (#35579)
Browse files Browse the repository at this point in the history
Currently the case where `r == 0` falls through the same logic as every
other non-negative value of `r` (aside from 1). This works for signed
integers. However, this does not work for unsigned integers: in the loop
where we unsafely fill in the output string, we're looping from 0 to `r
- 1`, which for unsigned integers wraps around and causes us to request
the address of the output string at a location that is well beyond what
was allocated.

Fixes #35578.
  • Loading branch information
ararslan authored Apr 24, 2020
1 parent 04cf2d5 commit 1dcb42f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
1 change: 1 addition & 0 deletions base/strings/substring.jl
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ end

function repeat(s::Union{String, SubString{String}}, r::Integer)
r < 0 && throw(ArgumentError("can't repeat a string $r times"))
r == 0 && return ""
r == 1 && return String(s)
n = sizeof(s)
out = _string_n(n*r)
Expand Down
20 changes: 11 additions & 9 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -668,15 +668,17 @@ end
@test_throws ArgumentError repeat(c, -1)
@test_throws ArgumentError repeat(s, -1)
@test_throws ArgumentError repeat(S, -1)
@test repeat(c, 0) === ""
@test repeat(s, 0) === ""
@test repeat(S, 0) === ""
@test repeat(c, 1) === s
@test repeat(s, 1) === s
@test repeat(S, 1) === S
@test repeat(c, 3) === S
@test repeat(s, 3) === S
@test repeat(S, 3) === S*S*S
for T in (Int, UInt)
@test repeat(c, T(0)) === ""
@test repeat(s, T(0)) === ""
@test repeat(S, T(0)) === ""
@test repeat(c, T(1)) === s
@test repeat(s, T(1)) === s
@test repeat(S, T(1)) === S
@test repeat(c, T(3)) === S
@test repeat(s, T(3)) === S
@test repeat(S, T(3)) === S*S*S
end
end
# Issue #32160 (string allocation unsigned overflow)
@test_throws OutOfMemoryError repeat('x', typemax(Csize_t))
Expand Down

0 comments on commit 1dcb42f

Please sign in to comment.