emalloc

emallocというのは,エラー処理付きのmalloc(2)関数で,メモリ確保に失敗したら,error関数を呼んで終了処理をしている.

   46: void
   47: error(char *s)
   48: {
   49:         fprint(2, "rio: %s: %r\n", s);
   50:         if(errorshouldabort)
   51:                 abort();
   52:         threadexitsall("error");
   53: }

   64: void*
   65: emalloc(uint n)
   66: {
   67:         void *p;
   68: 
   69:         p = malloc(n);
   70:         if(p == nil)
   71:                 error("malloc failed");
   72:         memset(p, 0, n);
   73:         return p;
   74: }

gonzuiで検索して,げげっと思ったのが,各コマンドがemallocやらereallocやらestrdupを持っていること.こんなコピペしまくるのなら,ライブラリにまとめちゃえばいいのに,と思った.同じ疑問を持った人がいたようで,9fansでも,same functions everywhereというスレッドができていた.これに対して,Rob Pike氏は,emallocはアプリ依存なので,ライブラリに入れるべきじゃないと主張した.なるほど,rioの場合は,error関数内でスレッドの後始末しているしなぁ.根本的な問題は,C言語にまともなエラー処理(例外処理)機構がないことかもしれないが.

The argument I think carries the day is that error handling is an
application-specific issue, not a library issue. I have written emalloc
several times but each application tends to do something different
in the error case. That is the real point.