Skip to content

Commit

Permalink
Fixed #3332: incorrect cast placement of to_u32
Browse files Browse the repository at this point in the history
Ary Borenszweig committed Sep 21, 2016

Verified

This commit was signed with the committer’s verified signature.
headius Charles Oliver Nutter
1 parent 9156f79 commit d657b9a
Showing 2 changed files with 8 additions and 1 deletion.
7 changes: 7 additions & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
@@ -1979,4 +1979,11 @@ describe "String" do
"foo".at(4)
end
end

it "allocates buffer of correct size when UInt8 is given to new (#3332)" do
String.new(255_u8) do |buffer|
LibGC.size(buffer).should be >= 255
{255, 0}
end
end
end
2 changes: 1 addition & 1 deletion src/string.cr
Original file line number Diff line number Diff line change
@@ -210,7 +210,7 @@ class String
def self.new(capacity : Int)
check_capacity_in_bounds(capacity)

str = GC.malloc_atomic((capacity + HEADER_SIZE + 1).to_u32).as(UInt8*)
str = GC.malloc_atomic(capacity.to_u32 + HEADER_SIZE + 1).as(UInt8*)

This comment has been minimized.

Copy link
@kostya

kostya Sep 21, 2016

Contributor

so after overflow there be a super big number? may be disallow big numbers in GC.malloc_atomic? like you already check it to 0

This comment has been minimized.

Copy link
@asterite

asterite Sep 21, 2016

Member

A 251 was passed, but this was a UInt8. So 251 + HEADER_SIZE + 1, is 251 + 12 + 1 = 264, but that doesn't fit in a UInt8, or yes, but it's implicitly an 8. So less memory then needed was allocated for the string, and it was written past it (to an unknown memory location)

buffer = str.as(String).to_unsafe
bytesize, size = yield buffer
str_header = str.as({Int32, Int32, Int32}*)

0 comments on commit d657b9a

Please sign in to comment.