memory allocation のトレース

アプリが落ちたのでコンソールを見ると、表示されるのは

EXEC_BAD_ACCESS

だけ!で困ったとき、以下の方法で原因発見できたのでそのメモです。

以下、シミュレータの場合です。実機の場合は以下を参照(要ログイン)
https://devforums.apple.com/message/10706#10706

設定
  • XCodeで、「グループとファイル」の「実行可能ファイル」の下のアプリケーションを選択
  • コンテクストメニューから「情報を見る」
  • 引数タブを選択
  • 「環境に設定される変数」に下記を追加
名前
NSZombieEnabled YES
MallocStackLogging YES
デバッグ

上記の設定をしたら、デバッグ実行します。
コンソールに以下のようなメッセージがでます。

appname(3375) malloc: stack logs being written into /tmp/stack-logs.3375.appname.wB32v3

エラーを再現します。
落ちると以下のようなメッセージが出力されました。

2010-10-05 06:56:53.419 appname[1756:20b] *** -[CALayer release]: message sent to deallocated instance 0x3e63250

malloc historyを見るには info malloc-history のコマンドをつかいます。 shell malloc_history というコマンドもありますが、前者の方が見やすそうです。

エラーメッセージの最後に出力されているのがアドレスをパラメータで指定します。上の出力の場合だと 0x3e63250 です。

(gdb) info malloc-history 0x3e63250
Stack - pthread: 0xa0168720 number of frames: 28
    0: 0x90ed98cd in malloc_zone_calloc
    1: 0x90ed9822 in calloc
    2: 0x96579618 in _internal_class_createInstanceFromZone
    3: 0x96582b08 in _internal_class_createInstance
    4: 0x9098fc in +[NSObject allocWithZone:]
    5: 0x9097ea in +[NSObject alloc]
    6: 0x16a618e in -[UIView _createLayerWithFrame:]
    7: 0x16a27b7 in UIViewCommonInitWithFrame
    8: 0x16a2ed8 in -[UIView initWithFrame:]
    9: 0x181c9a5 in -[UITableViewCell initWithStyle:reuseIdentifier:]
   10: 0x3a0c in -[Preferences tableView:cellForRowAtIndexPath:] at /Users/devel/iPhone/App/Hoge.m:108

正直なところ、あまり見方はわかってませんが、上から見ていって最初に出てくる自分のコードを疑うといいと思います。