【发布时间】:2019-12-15 04:19:55
【问题描述】:
我目前正在使用 glib-Testing 为我正在编写的 C 库进行单元测试。这些测试的一部分检查代码是否在预期的情况下失败(我习惯于来自 Python 的此类测试,您会在其中断言某个异常已引发)。我正在使用the manual for glib-Testing for g_test_trap_subprocess () 中的配方(请参见下面的最小示例),从单元测试的角度来看,它可以正常工作并提供正确的测试。
我的问题是当我在以下最小示例 (test_glib.c) 上运行 valgrind 时:
#include <glib.h>
void test_possibly_lost(){
if (g_test_subprocess()){
g_assert(1 > 2);
}
g_test_trap_subprocess(NULL, 0, 0);
g_test_trap_assert_failed();
}
int main(int argc, char **argv){
g_test_init(&argc, &argv, NULL);
g_test_add_func("/set1/test", test_possibly_lost);
return g_test_run();
}
编译
gcc `pkg-config --libs --cflags glib-2.0` test_glib.c
valgrind --leak-check=full ./a.out 的输出则为
==15260== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==15260== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==15260== Command: ./a.out
==15260==
/set1/test: OK
==15260==
==15260== HEAP SUMMARY:
==15260== in use at exit: 24,711 bytes in 40 blocks
==15260== total heap usage: 2,507 allocs, 2,467 frees, 235,121 bytes allocated
==15260==
==15260== 272 bytes in 1 blocks are possibly lost in loss record 36 of 40
==15260== at 0x483AB65: calloc (vg_replace_malloc.c:752)
==15260== by 0x4012AC1: allocate_dtv (in /usr/lib/ld-2.29.so)
==15260== by 0x4013431: _dl_allocate_tls (in /usr/lib/ld-2.29.so)
==15260== by 0x4BD51AD: pthread_create@@GLIBC_2.2.5 (in /usr/lib/libpthread-2.29.so)
==15260== by 0x48BE42A: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260== by 0x48BE658: g_thread_new (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260== by 0x48DCBF0: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260== by 0x48DCC43: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260== by 0x48DCD11: g_child_watch_source_new (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260== by 0x48B7DF4: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260== by 0x48BEA93: g_test_trap_subprocess (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260== by 0x1091DD: test_possibly_lost (in /dir/to/aout/a.out)
==15260==
==15260== LEAK SUMMARY:
==15260== definitely lost: 0 bytes in 0 blocks
==15260== indirectly lost: 0 bytes in 0 blocks
==15260== possibly lost: 272 bytes in 1 blocks
==15260== still reachable: 24,439 bytes in 39 blocks
==15260== suppressed: 0 bytes in 0 blocks
==15260== Reachable blocks (those to which a pointer was found) are not shown.
==15260== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==15260==
==15260== For counts of detected and suppressed errors, rerun with: -v
==15260== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
可能丢失的内存困扰着我,巧合的是我的代码也可能丢失 272 个字节,所以我认为这可能是我使用 glib 的方式而不是我自己的结构的问题。就个人而言,我会将可能丢失的记忆视为绝对丢失,我想摆脱它。
所以我的问题是,我是否可以巧妙地插入一个 free 来释放内存,是否有一个不同的方法来检查失败的断言,或者这些丢失的 272 个字节只是我必须忍受的吗?
【问题讨论】:
-
如何从 Valgrind 的建议开始,使用
--leak-check=full重新运行以获取(可能)泄漏内存的详细信息?大概它会指向 glib 中的某些内容,但您应该更好地了解您正在处理的内容。如果事实证明这是最好的替代方案,这也将使您准备好编写 Valgrind 抑制文件。 -
是的,我在发布问题后意识到我忘记在我的最小示例中包含该标志,我更新了问题,谢谢!
标签: c unit-testing valgrind glib