Skip to content

Commit

Permalink
Use GC.malloc_atomic with GC.realloc, not Pointer#realloc (#12391)
Browse files Browse the repository at this point in the history
  • Loading branch information
HertzDevil authored Aug 30, 2022
1 parent f9f3b80 commit f2e0b71
Show file tree
Hide file tree
Showing 6 changed files with 12 additions and 6 deletions.
2 changes: 1 addition & 1 deletion spec/std/io/io_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ private class SimpleIOMemory < IO

private def resize_to_capacity(capacity)
@capacity = capacity
@buffer = @buffer.realloc(@capacity)
@buffer = GC.realloc(@buffer, @capacity)
end
end

Expand Down
7 changes: 5 additions & 2 deletions src/gc.cr
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ module GC
# If *pointer* was allocated with `malloc_atomic`, the same constraints apply.
#
# The return value is a pointer that may be identical to *pointer* or different.
def self.realloc(pointer : Void*, size : Int) : Void*
realloc(pointer, LibC::SizeT.new(size))
#
# WARNING: Memory allocated using `Pointer.malloc` must be reallocated using
# `Pointer#realloc` instead.
def self.realloc(pointer : T*, size : Int) : T* forall T
realloc(pointer.as(Void*), LibC::SizeT.new(size)).as(T*)
end
end

Expand Down
2 changes: 1 addition & 1 deletion src/io/memory.cr
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,6 @@ class IO::Memory < IO

private def resize_to_capacity(capacity)
@capacity = capacity
@buffer = @buffer.realloc(@capacity)
@buffer = GC.realloc(@buffer, @capacity)
end
end
3 changes: 3 additions & 0 deletions src/pointer.cr
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,9 @@ struct Pointer(T)
# ptr = ptr.realloc(8)
# ptr # [1, 2, 3, 4, 0, 0, 0, 0]
# ```
#
# WARNING: Memory allocated using `GC.malloc` or `GC.malloc_atomic` must be
# reallocated using `GC.realloc` instead.
def realloc(size : Int)
if size < 0
raise ArgumentError.new("Negative size")
Expand Down
2 changes: 1 addition & 1 deletion src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ class String

# Try to reclaim some memory if capacity is bigger than what was requested
if bytesize < capacity
str = str.realloc(bytesize.to_u32 + HEADER_SIZE + 1)
str = GC.realloc(str, bytesize.to_u32 + HEADER_SIZE + 1)
end

str_header = str.as({Int32, Int32, Int32}*)
Expand Down
2 changes: 1 addition & 1 deletion src/string/builder.cr
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,6 @@ class String::Builder < IO

private def resize_to_capacity(capacity)
@capacity = capacity
@buffer = @buffer.realloc(@capacity)
@buffer = GC.realloc(@buffer, @capacity)
end
end

0 comments on commit f2e0b71

Please sign in to comment.