c言語プログラムのメモリチェックをvalgrindで
5月 15th, 2008 Posted in c言語
まずvalgrindの導入.
ubuntu-linuxであれば
sudo apt-get install valgrindで入れることができる.
使いかたは,簡単.
まずプログラムを書いて,-gオプションをつけてコンパイルします.
gcc -g hoge.cそして,チェック
valgrind ./a.outではこれで実際どのようになるのか,簡単な例で見てみましょう.
hoge.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *num = malloc(10*sizeof(int));
num[10] = '1';
}
配列を越えて書き込んでいます.これをチェックすると
==3734== Invalid write of size 4==3734== at 0x804839A: main (hoge.c:7) ==3734== Address 0x417B050 is 0 bytes after a block of size 40 alloc'd ==3734== at 0x4021620: malloc (vg_replace_malloc.c:149) ==3734== by 0x8048390: main (hoge.c:6) ==3734== ==3734== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 11 from 1) ==3734== malloc/free: in use at exit: 40 bytes in 1 blocks. ==3734== malloc/free: 1 allocs, 0 frees, 40 bytes allocated. ==3734== For counts of detected errors, rerun with: -v ==3734== searching for pointers to 1 not-freed blocks. ==3734== checked 59,628 bytes.などど出て,hoge.cの6行目で不正なメモリアクセスがあるとわかります.
本当はもっとたくさん文章が出てきます.
ですが,この程度のチェックならコンパイル時に
gcc -Wall -g hoge.cとすれば,はじいてくれます.-Wallオプションもいつもつけるようにしましょう.
関連する投稿
tags: c言語
