LoginSignup
13
9

More than 1 year has passed since last update.

[C言語] leaksコマンドを使った簡単なメモリリークの確認方法

Last updated at Posted at 2021-08-12

C言語でプログラムを書いているとメモリリークがよく発生します。
そのため、なるべく簡単にメモリリークを確認する方法を調べてみました。
方法として2つ紹介させて頂きます。

1. デストラクターを設定する

コマンドを設定することでプロセスが終了時に自動的に実行されます。

#include <libc.h>

__attribute__((destructor))
static void destructor() {
    system("leaks -q a.out");
}

int main()
{
    char *s = malloc(100);

    s = "hello world";
    puts(s);
    return (0);
}

実行結果

$ gcc test.c
$ ./a.out 
hello world
leaks Report Version: 4.0
Process 47921: 170 nodes malloced for 13 KB
Process 47921: 1 leak for 112 total leaked bytes.

    1 (112 bytes) ROOT LEAK: 0x7ff7f7c05af0 [112]

leaksコマンドが実行されていますね。
ちなみに -q オプションを付けることでヘッダとフッタを非表示にしています。

2. 実行時に-atExitオプションを付ける

#include <libc.h>

int main()
{
    char *s = malloc(100);

    s = "hello world";
    puts(s);
    return (0);
}

実行結果

$ gcc test.c
$ leaks -q -atExit -- ./a.out
hello world
leaks Report Version: 4.0
Process 48537: 170 nodes malloced for 13 KB
Process 48537: 1 leak for 112 total leaked bytes.

    1 (112 bytes) ROOT LEAK: 0x7fcba3c05af0 [112]

leaksコマンドがatExitとして設定されてプロセスが終了時に実行されています。
aliasに設定しておけば手っ取り早く確認できるので便利ですね。

まとめ

メモリリークは避けては通れないので、逐一確認していくと良さそうですね。
man leaksで他にも便利なオプションが見れるので興味ある方は是非試してみてください。

13
9
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
13
9