From: Tim Elliott Date: 2011-02-04T08:24:57+09:00 Subject: [ruby-core:35079] allocate vs. initialize & JSON segfault I am not sure where to allocate and where to initialize a C struct. I see a few variations in ruby's 1.9.2 source code: * Allocate C struct in the allocate method and initialize C struct values in the initialize method. (JSON::Parser) * Allocate & initialize C struct in the allocate method. (OpenSSL::Cipher) * Allocate & initialize C struct in the initialize method. (DBM) README.EXT says: void rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE klass)); func has to take the klass as the argument and return a newly allocated instance. This instance should be as empty as possible, without any expensive (including external) resources. Which indicates that it is preferable for the allocate method to do as little as possible. However, if you leave the allocated C struct uninitialized it can lead to unknown state when an object's initialize method is overridden. For example, this code will crash the ruby 1.9.2 interpreter: require 'json' module JSON class Parser def initialize; end end end parser = JSON::Parser.new parser.source # => [BUG] Segmentation fault Is there a preferred approach? Is the JSON example a bug, or should a script never override a C initializer without super? Cheers, Tim