2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C言語 メモリリーク検出ツール

Last updated at Posted at 2020-11-27

はじめに

メモリリークを確認するツールが紹介されていたので、自分用に要点をまとめた記事です。

こちらのコードは以下のサイトで解説されていたコードに少し手を加えて、使っています。
以下サイトは解説等も充実しておりますので、詳しくはそちらをお読みください。

【C言語】メモリの解放忘れ(メモリリーク)を自力で検出する方法 | だえうホームページ

ツールのコード

メモリリークを検出したいファイルと一緒にコンパイルするコード

leakdetect.c
# include <stdio.h>
# include <stdlib.h>
# include "leakdetect.h"

# define N 500

MEM_T mi[N];

void leak_detect_init()
{
	for (int i = 0; i < N; i++)
	{
		mi[i].p = NULL;
		mi[i].size = 0;
		mi[i].file = NULL;
		mi[i].line = 0;
	}
}

void *leak_detelc_malloc(size_t size, const char *file, unsigned int line)
{
	void *p;

	if (!(p = malloc(size)))
		return NULL;
	for (int i = 0; i < N; i++)
	{
		if (mi[i].p == NULL)
		{
			mi[i].p = p;
			mi[i].size = size;
			mi[i].file = file;
			mi[i].line = line;
			break;
		}
	}
	return p;
}

void leak_detect_free(void *p)
{
	for (int i = 0; i < N; i++)
	{
		if (mi[i].p == p)
		{
			mi[i].p = NULL;
			mi[i].size = 0;
			mi[i].file = NULL;
			mi[i].line = 0;
			break;
		}
	}
	free(p);
	p = NULL;
}

void leak_detect_check()
{
	for (int i = 0; i < N; i++)
	{
		if (mi[i].p != NULL)
		{
			printf("=== memory leak ===\n");
			printf(" adress : %p\n", mi[i].p);
			printf(" size   : %u\n", (unsigned int)mi[i].size);
			printf(" where  : %s:%u\n", mi[i].file, mi[i].line);
			printf("===================\n\n");
		}
	}
}
leakdetect.h
# ifndef LEAKDETECT_H
# define LEAKDETECT_H
# include <stdlib.h>

typedef struct
{
    void *p;
    size_t size;
    const char *file;
    unsigned int line;
} MEM_T;

void leak_detect_init(void);
void *leak_detelc_malloc(size_t, const char*, unsigned int);
void leak_detect_free(void*);
void leak_detect_check(void);

# endif

使い方

①mallocとfreeを使う関数の冒頭部分にマクロを追記。
②main関数の中にテストしたいコードを挟むように
leak_detect_init();leak_detect_cheak();を追記。

main.c
# include "leakdetect.h"
# define malloc(s) leak_detelc_malloc(s, __FILE__, __LINE__)
# define free leak_detect_free

int main()
{
	leak_detect_inti();

	// ~~~ 確認したいコード ~~~

	leak_detect_cheak();

	return 0;

巻き込んでコンパイル

gcc main.c leakdetect.c
2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?