Summary: A Ruby/RMagick script of mine was failing with a variety of “Cannot allocate memory” errors. Adding a single line to the bottom of my thumbnail generation loop fixed this: img.destroy!.
Problem: It all started with a segmentation fault. Ruby, segfaulting? Since it was on a garbage GoDaddy VPS running Fedora Core 7, all of the packages were horribly out of date, so I recompiled everything from scratch: Ruby 1.9.1p0, ImageMagick-6.5.1-2, RMagick 2.9.1 (read about that fiasco here). That got the segmentation fault replaced by a variety of errors, such as:
in write': MemoryAllocationFailedCannot allocate memory’ @
string.c/AcquireStringInfo/173 (Magick::FatalImageMagickError)in resize!': MemoryAllocationFailedphotos/1066.jpg[0]’ @
cache.c/AcquireCacheNexusPixels/457 (Magick::ImageMagickError)in resize!': UnableToAcquireStringCannot allocate memory’ @
string.c/AcquireString/126 (Magick::FatalImageMagickError)in read': MemoryAllocationFailedCannot allocate memory’ @
image.c/AcquireImage/155 (Magick::FatalImageMagickError)Solution: My thumbnail creation loop was creating a bunch of Magick::Image objects, and not deleting them. In this case, we must supplement Ruby’s garbage collector by explicitly deleting the objects:
img.destroy!
Discussion: See this forum post for an explanation why Ruby’s garbage collector isn’t doing what we expect it to.