In message "Re: [ruby-core:21161] [Bug #985] profile lib + iterator => 'NULL pointer given' (ArgumentError)"
    on Tue, 6 Jan 2009 08:54:03 +0900, Alex Fenton <redmine / ruby-lang.org> writes:

|This simple piece of code works as expected:
|
|iter = 'abc'.each_char
|p iter.next
|=> "a"
|
|However, if the profile library is required before this (either by -rprofile on the command line or require 'profile') it crashes with an unexpected 'NULL pointer given' error:
|
|ruby -rprofile bug.rb 
|  %   cumulative   self              self     total
| time   seconds   seconds    calls  ms/call  ms/call  name
|  0.00     0.00      0.00        2     0.00     0.00  IO#set_encoding
|  0.00     0.00      0.00        1     0.00     0.00  String#each_char
|  0.00     0.00      0.00        1     0.00     0.00  Kernel.proc
|  0.00     0.00      0.00        1     0.00     0.00  Exception#backtrace
|  0.00     0.00      0.00        1     0.00     0.00  Exception#set_backtrace
|  0.00     0.01      0.00        1     0.00    10.00  #toplevel
|bug.rb:2:in `next': NULL pointer given (ArgumentError)
|	from bug.rb:2:in `<main>'

The direct reason is that rb_sourcefile() returns NULL.  The attached
patch will fix the problem, but I am not sure yet why rb_sourcefile()
(and why vm_get_ruby_level_next_cfp) gives us NULL.  I hope Koichi has
the answer.

							matz.
--- a/thread.c
+++ b/thread.c
@@ -3545,12 +3545,15 @@ call_trace_proc(VALUE args, int tracing)
 {
     struct call_trace_func_args *p = (struct call_trace_func_args *)args;
     VALUE eventname = rb_str_new2(get_event_name(p->event));
-    VALUE filename = rb_str_new2(rb_sourcefile());
+    const char *fname = rb_sourcefile();
+    VALUE filename;
     VALUE argv[6];
     int line = rb_sourceline();
     ID id = 0;
     VALUE klass = 0;
 
+    if (fname) filename = rb_str_new2(fname);
+    else filename = Qnil;
     if (p->event == RUBY_EVENT_C_CALL ||
 	p->event == RUBY_EVENT_C_RETURN) {
 	id = p->id;
@@ -3574,7 +3577,7 @@ call_trace_proc(VALUE args, int tracing)
     argv[1] = filename;
     argv[2] = INT2FIX(line);
     argv[3] = id ? ID2SYM(id) : Qnil;
-    argv[4] = p->self ? rb_binding_new() : Qnil;
+    argv[4] = p->self && fname ? rb_binding_new() : Qnil;
     argv[5] = klass ? klass : Qnil;
 
     return rb_proc_call_with_block(p->proc, 6, argv, Qnil);