LoginSignup
6
4

More than 5 years have passed since last update.

Ruby + MeCab で Segmentation fault が発生した場合の対処

Posted at

はじめに

MeCab の標準の Ruby 用バインディングを利用してテキスト解析を行っていたら、
hoge.rb:XX: [BUG] Segmentation fault at 0x00123456789abc
のようなエラーが発生した。

発生したタイミングは次の通り。
・処理が一定の負荷を超えた場合、毎回そこで落ちる。
・軽い処理の場合は落ちない。

落ちてた部分は下記の行。
node = MeCab::Tagger.new.parseToNode(string)

Python で同様の事例

以前 Python で意図しないガベージコレクションが実行されることにより、
似たような事例が発生した事があった。

(この件は次のサイトが詳しくまとめてくれている Shogo's Blog: MeCabをPythonから使う注意点とか)

対処

Ruby でも同じことが起きてるんじゃないかと思ったので、コードを書き換えた。
いきなり node を作らず、MeCab::Tagger.new を一度適当な変数に代入する。

before
require 'mecab'

node = MeCab::Tagger.new.parseToNode(string)
while node
  ...
after
require 'mecab'

m = MeCab::Tagger.new
node = m.parseToNode(string)
while node
  ...

これで無事に問題が発生しなくなった。

おわりに

無事問題は解決した。
おそらく他の言語でも似たような事例が発生する可能性あり。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4