XcodeでC言語のメモリリークを検出
移転しました →
久しぶりにmallocするプログラムを書いているのでメモリリークが怖い。そこでXcodeのInstrumentsによるメモリリークの検出が本当にできるかどうかを簡単な例で試しておくことにした。これでいざというときに使える。
まず普通に構造体を定義する。
/* Sample.h */ #ifndef __MemLeak__Sample__ #define __MemLeak__Sample__ #include <string> typedef struct _sample_ { std::string a; std::string b; std::string c; std::string d; std::string e; std::string f; std::string g; std::string h; } Sample, *SampleP; #endif /* defined(__MemLeak__Sample__) */
メイン関数ではmalloc
するだけして解放しないということを1秒毎に繰り返してみる。
/* main.cpp */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "Sample.h" SampleP CreateSample() { printf("sample created\n"); return (SampleP)malloc(sizeof(Sample)); } int main(int argc, const char * argv[]) { while(true){ SampleP p = CreateSample(); printf("%s\n", p->c.c_str()); sleep(1); } return 0; }
そしてInstrumentsをコマンド+I
で起動し、Leaksを選ぶ。
するとプログラムが動き出し、Instrumentsの画面には次々にメモリ確保がなされる様子と時々Leakした様子が表れる。
Leakしたオブジェクトの一覧を見てみると、ちゃんとCreateSample
で確保したメモリがリークしてるよと教えてくれている。
ちゃんとC言語のコードでも動いていることが確認できた。よかった!