久しぶりにmallocするプログラムを書いているのでメモリリークが怖い。そこでXcodeのInstrumentsによるメモリリークの検出が本当にできるかどうかを簡単な例で試しておくことにした。これでいざというときに使える。

まず普通に構造体を定義する。

 1/* Sample.h */
 2#ifndef __MemLeak__Sample__
 3#define __MemLeak__Sample__
 4
 5#include <string>
 6
 7typedef struct _sample_
 8{
 9    std::string a;
10    std::string b;
11    std::string c;
12    std::string d;
13    std::string e;
14    std::string f;
15    std::string g;
16    std::string h;
17} Sample, *SampleP;
18
19#endif /* defined(__MemLeak__Sample__) */

メイン関数ではmallocするだけして解放しないということを1秒毎に繰り返してみる。

 1/* main.cpp */
 2#include <stdio.h>
 3#include <stdlib.h>
 4#include <unistd.h>
 5#include "Sample.h"
 6
 7SampleP CreateSample()
 8{
 9    printf("sample created\n");
10    return (SampleP)malloc(sizeof(Sample));
11}
12
13int main(int argc, const char * argv[])
14{
15    while(true){
16        SampleP p = CreateSample();
17        printf("%s\n", p->c.c_str());
18        sleep(1);
19    }
20    return 0;
21}

そしてInstrumentsをコマンド+Iで起動し、Leaksを選ぶ。

するとプログラムが動き出し、Instrumentsの画面には次々にメモリ確保がなされる様子と時々Leakした様子が表れる。

Leakしたオブジェクトの一覧を見てみると、ちゃんとCreateSampleで確保したメモリがリークしてるよと教えてくれている。

ちゃんとC言語のコードでも動いていることが確認できた。よかった!