Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging malloc errors in Ruby on Mac OS X

I'm trying to debug errors like the following that I get while running some Ruby scripts:

ruby(47333,0x7fff72aee960) malloc: *** error for object 0x7f98b6a6e3f0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

Any idea how I can actually set such a breakpoint and debug? I want to see whether this is caused by Ruby itself or some extensio..

I'm Using Mac OS X 10.7.3 (Lion) and ruby 1.8.7 (2010-01-10 patchlevel 249) [universal-darwin11.0].

like image 371
bgcode Avatar asked Jun 06 '12 21:06

bgcode


1 Answers

If you are on Ruby 1.9.2+, install the debugger gem (gem install debugger). There are two ways to debug: directly including the debugger gem or using the redbug binary. Let's pretend we have a toy script, and we want to know why $blah is 4 after calling foo() (pretend it's an external library).

Method 1: Including debugger

This is setting a breakpoint manually in your code:

require 'debugger'

$blah = 3

def foo
  $blah += 1
end

def bar
  $blah += 4
end

foo()
debugger() # opens rdb
bar()

puts $blah

Run this as ruby debug.rb. This will launch you into a ruby-debug console:

% ruby debug.rb
debug.rb:15
bar()
(rdb:1) list
[10, 19] in debug.rb
   10    $blah += 4
   11  end
   12  
   13  foo()
   14  debugger()
=> 15  bar()
   16  
   17  puts $blah
(rdb:1) display $blah
1: $blah = 4

Method 2: Running rdebug

Here's our example example script, debug.rb:

$blah = 3

def foo
  $blah += 1
end

def bar
  $blah += 4
end

foo()
bar()

puts $blah

From shell, execute rdebug debug.rb. Here's an example session:

% rdebug debug.rb
(rdb:1) list 1,20
[1, 20] in /mnt/hgfs/src/stackoverflow/debug.rb
=> 1  $blah = 3
   2  
   3  def foo
   4    $blah += 1
   5  end
   6  
   7  def bar
   8    $blah += 4
   9  end
   10  
   11  foo()
   12  bar()
   13  
   14  puts $blah
(rdb:1) break 12
Breakpoint 1 file /mnt/hgfs/src/stackoverflow/debug.rb, line 12
(rdb:1) display $blah
1: $blah = 
(rdb:1) continue
Breakpoint 1 at /mnt/hgfs/src/stackoverflow/debug.rb:12
1: $blah = 4
/mnt/hgfs/src/stackoverflow/debug.rb:12
bar()
(rdb:1) display $blah
2: $blah = 4

The key commands are break LINE-NUMBER and display VARIABLE. Hope that helps!

Resources

  • ruby-debug documentation
  • debugger gem
like image 79
jmdeldin Avatar answered Oct 12 '22 13:10

jmdeldin