Skip to content

Instantly share code, notes, and snippets.

@bew
Last active May 5, 2017 01:22
Show Gist options
  • Save bew/20a45cb3c6cbeb3fb88fcf48c383e4ea to your computer and use it in GitHub Desktop.
Save bew/20a45cb3c6cbeb3fb88fcf48c383e4ea to your computer and use it in GitHub Desktop.
Test for OutOfMemory exception
Kilobyte = 1024u32
Megabyte = 1024u32 * Kilobyte
Gigabyte = 1024u32 * Megabyte
def write_debug(str)
LibC.write 1, str, str.size
end
class FatalOOMError < Exception
def initialize
super "pre-allocated OOM"
end
end
class OOMError < Exception
@@oom_pending = false
@@fatal_oom = FatalOOMError.new # pre-allocated error
def self.try_new
if @@oom_pending
write_debug "oom raise failed\n"
return @@fatal_oom
end
@@oom_pending = true
oom = new
@@oom_pending = false
write_debug "oom error..\n"
oom
end
def initialize
super "dynamically-allocated OOM"
Pointer(Void).malloc(Megabyte) # simulate an alloc to crash on very low memory
end
end
fun __crystal_malloc(size : UInt32) : Void*
ptr = LibGC.malloc size
if ptr.null?
write_debug "null!\n"
raise OOMError.try_new
end
ptr
end
module Test
class_getter gb_alloced = 0
class_getter mb_alloced = 0
def self.giga
__crystal_malloc(Gigabyte)
@@gb_alloced += 1
write_debug "giga "
end
def self.mega
__crystal_malloc(Megabyte)
@@mb_alloced += 1
write_debug "mega "
end
end
#------------------------------
GC.disable
loop do
begin
Test.giga
rescue ex : OOMError
puts "---------------------------------------"
puts "Got an OOMError!!"
puts "---------------------------------------"
break
end
end
loop do
begin
Test.mega
rescue ex : FatalOOMError
puts "---------------------------------------------"
puts "Got a FatalOOMError!! Almost no memory left!"
puts "---------------------------------------------"
break
end
end
puts
puts "alloc'ed: #{Test.gb_alloced}G #{Test.mb_alloced}M"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment