From: Jeff Davis Date: 2008-07-07T02:24:42+09:00 Subject: Re: mysterious memory corruption, very confused On Mon, 2008-06-30 at 15:47 +0900, Seebs wrote: > On 2008-06-30, Roger Pack wrote: > >> I get random data corruption when trying to execute queries. > > valgrind might tell you if memory is being tramped. > > It is. There's a loop of > VALUE x; > char **foo = malloc(buncha char *); > > for (big list of things) { > x = rb_obj_as_string(y); > foo[i] = GetStringValue(x); > } > > The idiom of using rb_obj_as_string, and then using the value, is common in > the Ruby source. It works. ... It works *as long as you don't allocate > anything more before you're done with it*. What ends up happening is that, > if enough of the objects in question need a new string allocated by > rb_obj_as_string, sooner or later you end up invoking the garbage collector. > Now, since there's only one x, the garbage collector assumes the current > rb_obj_as_string() return is in use, *and the others aren't*. So it might, > if it wants the space, free one... And then the memory gets reused. Thanks again for the detailed analysis. To be clear, you're saying that the new object created by rb_obj_as_string() can be freed as soon as I allocate any new ruby object? Is this documented behavior? To be safe, should I always assume any object that I allocate in C land lives only until the next object is allocated (unless it's referenced by some other object Ruby knows about, of course)? Regards, Jeff Davis