Ruby, C, and garbage collection

VALUE a, b, c;

a = rb_some_function_1();
b = rb_some_function_2();
c = rb_do_something(a,b);

In this code, if Ruby decides to do GC during rb_some_function_2,
`a’ will be destroyed, and it will segfault at rb_do_something.

Well, real code that segfaults is a bit more complex, but the problem
is the same - after allocation of one variable, GC is run,
and another variable is destroyed, and then it segfaults
trying to use destroyed variable.

How to overcome that ?

Hi,

VALUE a, b, c;

a = rb_some_function_1();
b = rb_some_function_2();
c = rb_do_something(a,b);

In this code, if Ruby decides to do GC during rb_some_function_2,
`a’ will be destroyed, and it will segfault at rb_do_something.

I don’t think so. Ruby uses conservative GC, which scans C stack
region to protect Ruby object reference, so that an object referred
from the variable a is not destroyed.

But in some cases, local variables may vanish before function
terminates, for example:

VALUE a;
char *p

a = function_returns_string();
p = RSTRING(a)->ptr;
… process goes on referring p, but no a …

in such cases, an object referred from a might be reclaimed.
For a workaround, you can declare a as

volatile VALUE a;

to turn off too much optimization.

						matz.
···

In message “Ruby, C, and garbage collection” on 03/01/23, Tomasz Wegrzanowski taw@users.sf.net writes:

Hi,

···

At Thu, 23 Jan 2003 12:16:34 +0900, Yukihiro Matsumoto wrote:

But in some cases, local variables may vanish before function
terminates, for example:

VALUE a;
char *p

a = function_returns_string();
p = RSTRING(a)->ptr;
… process goes on referring p, but no a …

in such cases, an object referred from a might be reclaimed.
For a workaround, you can declare a as

volatile VALUE a;

to turn off too much optimization.

Or use StringValuePtr() provided for such cases.


Nobu Nakada

I don’t understand. How would using StringValuePtr() help in these
cases?

Paul

···

On Thu, Jan 23, 2003 at 03:23:27PM +0900, nobu.nokada@softhome.net wrote:

At Thu, 23 Jan 2003 12:16:34 +0900, > Yukihiro Matsumoto wrote:

For a workaround, you can declare a as

volatile VALUE a;

to turn off too much optimization.

Or use StringValuePtr() provided for such cases.

Hi,

···

In message “Re: Ruby, C, and garbage collection” on 03/01/24, Paul Brannan pbrannan@atdesk.com writes:

Or use StringValuePtr() provided for such cases.

I don’t understand. How would using StringValuePtr() help in these
cases?

The macro StringValuePtr() uses the variable’s address internally, so
that the variable will not be optimized out before function
termination.

						matz.