LoginSignup
1
1

More than 1 year has passed since last update.

C言語 __attribute__((destructor))を使用したメモリリークチェック

Last updated at Posted at 2021-07-04

関数属性を使ったデバッグ方法

__attribute__((destructor))を使用して、属性を付与します。
デストラクタ属性により、main()が完了した後、またはexit()が呼び出された後、関数が自動的に呼び出されます。

コードと使用方法

以下のコードを記述したファイルを別途作成し、コンパイル時に巻き込んで、実行します。

リークがある場合は、標準エラー出力とleaksoutというファイルにエラーログが出力されます。

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

__attribute__((destructor))
void    destructor(void)
{
    int     status;
    char    buf[50];

    snprintf(buf, 50, "leaks %d &> leaksout", getpid());
    status = system(buf);
    if (status)
    {
        write(2, "leak!!!\n", 8);
        system("cat leaksout >/dev/stderr");
        exit(1);
    }
}

以下のようにして、宣言と定義を分けて書くこともできます。

void end(void)__attribute__((destructor));

void end(void)
{
    system("leaks pipex");
}

参考

Function Attributes - Using the GNU Compiler Collection (GCC)

1
1
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
1
1