查找 malloc 和 free 是否配对
说明
因为项目有老代码所以才需要这样处理,一般建议用 RAII 等技术避免裸露资源。
find_malloc.sh
要点:
- 用 gcc 去除代码注释。
- 用 awk 对正则表达式计数。
check() {
gcc -fpreprocessed -dD -E -P "$1" 2>/dev/null | awk -v file="$1" '
BEGIN {
malloc=0;
free=0;
queueCreate=0;
queueDestroy=0;
notifierCreate=0;
notifierDestroy=0;
handleCreate=0;
handleDestroy=0;
}
/cnrtMalloc\(/ { malloc++; }
/cnrtFree\(/ { free++; }
/cnrtQueueCreate\(/ { queueCreate++; }
/cnrtCreateQueue\(/ { queueCreate++; }
/cnrtDestroyQueue\(/ { queueDestroy++; }
/cnrtQueueDestroy\(/ { queueDestroy++; }
/cnrtCreateNotifier\(/ { notifierCreate++; }
/cnrtDestroyNotifier\(/ { notifierDestroy++; }
/cnnlCreate\(/ { handleCreate++; }
/cnnlDestroy\(/ { handleDestroy++; }
END {
if (malloc != free) {
print "file: " file ", malloc: " malloc ", free: " free
}
if (queueCreate != queueDestroy) {
print "file: " file ", queueCreate: " queueCreate ", queueDestroy: " queueDestroy
}
if (notifierCreate != notifierDestroy) {
print "file: " file ", notifierCreate: " notifierCreate ", notifierDestroy: " notifierDestroy
}
if (handleCreate != handleDestroy) {
print "file: " file ", handleCreate: " handleCreate ", handleDestroy: " handleDestroy
}
}'
}
check $1
find_malloc_all.sh
要点:使用 find
匹配时应该选择正则表达式类型,同时和 Python 的 re
模块一样要全字符串匹配(不能匹配只部分字符,因此想只匹配中间部分的时候,就要在两边加上 .*
)。
find src/ include/ -regextype egrep -regex '.*\.(h|hpp|cc|cpp)' -exec bash find_malloc.sh {} \;