# Rb\_protect / rb\_eval\_string and the GC in Ruby 1.8.7

**URL:** <https://www.ruby-forum.com/t/rb-protect-rb-eval-string-and-the-gc-in-ruby-1-8-7/160245>\
**Category:** Ruby\
**Created:** [February 13, 2009, 11:26am UTC](https://www.ruby-forum.com/t/rb-protect-rb-eval-string-and-the-gc-in-ruby-1-8-7/160245 "2009-02-13T11:26:53Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tobias](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/c67d28/32.png) [@tobias](https://www.ruby-forum.com/u/tobias)\
**Post date:** [February 13, 2009, 11:26am UTC](https://www.ruby-forum.com/t/rb-protect-rb-eval-string-and-the-gc-in-ruby-1-8-7/160245/1 "2009-02-13T11:26:53Z")

</div>

Hi!

At the moment I’m trying to extend an application with embedded Ruby and  
therefore try to understand the garbage collection mechanisms.

For a simple class that just prints when it’s ctor and dtor are called,  
I’ve created the Ruby wrapping code with Swig. Now I do this:

in Ruby:

def get\_new\_bar  
puts “DEBUG: get\_new\_bar”  
return Swig::Bar.new  
end

In C++:

…  
rb\_eval\_string(“get\_new\_bar”);  
rb\_eval\_string(“puts 'DEBUG: '; GC.start; puts 'DEBUG: '”);  
…  
ruby\_finalize();

What happens is exactly, what one would expect:

DEBUG: Bar::Bar()  
DEBUG: get\_new\_bar  
DEBUG:   
DEBUG: Bar::~Bar();  
DEBUG:

Now I change this to:

…  
rb\_protect(get\_new\_bar\_eval\_wrapper, 0, &error);  
rb\_eval\_string(“puts 'DEBUG: '; GC.start; puts 'DEBUG: '”);  
…  
ruby\_finalize();

But what happens now is:

DEBUG: Bar::Bar()  
DEBUG: get\_new\_bar  
DEBUG:   
DEBUG:   
DEBUG: Bar::~Bar();

As soon as I call rb\_protect() a second time with completely different  
code, the object allocated in the previous rb\_protect call will be  
deleted  
in the next GC run.

The question is: Why doesn’t the GC delete the Bar instance when I  
create  
it within rb\_protect()? Is the Bar instance referenced by a global  
variable somewhere? Are there any threading issues I should be aware of  
with rb\_protect()?

This only happens in Ruby 1.8.7. In 1.9.0 there is no difference between  
the direct call and the rb\_protect wrapped call.

Thx,

Tobias
