【问题标题】:Valgrind Memcheck OutputValgrind Memcheck 输出
【发布时间】:2014-04-08 06:42:30
【问题描述】:

我正在使用 valgrind 来查找我的系统上的内存泄漏,我收到了这个输出

==9697== Memcheck, a memory error detector
==9697== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==9697== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==9697== Command: bin/vfirewall-monitor
==9697== 
==9697== 
==9697== HEAP SUMMARY:
==9697==     in use at exit: 0 bytes in 0 blocks
==9697==   total heap usage: 1 allocs, 1 frees, 37 bytes allocated
==9697== 
==9697== All heap blocks were freed -- no leaks are possible
==9697== 
==9697== For counts of detected and suppressed errors, rerun with: -v
==9697== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
==9700== Thread 2:
==9700== Conditional jump or move depends on uninitialised value(s)
==9700==    at 0x56DE3B1: vfprintf (vfprintf.c:1630)
==9700==    by 0x5706441: vsnprintf (vsnprintf.c:120)
==9700==    by 0x56E6971: snprintf (snprintf.c:35)
==9700==    by 0x403A1A: save_interfaces_info (interfaces.c:351)
==9700==    by 0x403DC4: get_all_system_info (kernel.c:135)
==9700==    by 0x547DE99: start_thread (pthread_create.c:308)
==9700==    by 0x57873FC: clone (clone.S:112)
==9700==  Uninitialised value was created by a heap allocation
==9700==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9700==    by 0x403D6F: get_all_system_info (kernel.c:118)
==9700==    by 0x547DE99: start_thread (pthread_create.c:308)
==9700==    by 0x57873FC: clone (clone.S:112)
==9700== 

它说没有错误,但我在 kernel.c:118 上有一个未初始化的值。

这是我在 118 的 1kernel.c1:

117    Interface * ifaces;
118    ifaces = malloc(sizeof (Interface));
119    ifaces->next_interface = NULL;

我不明白这里有什么问题。我找错地方了吗?还是我读错了 valgrind 日志?

【问题讨论】:

    标签: c linux memory-management profiling valgrind


    【解决方案1】:

    错误在interfaces.c:351,它使用未初始化的值调用snprintf

    该值是使用mallockernel.c:118 分配的。您可能知道,malloc 不会初始化它返回的内存,它可能包含垃圾。这就是它所抱怨的。

    您的Interface 对象很可能有一个char name[] 或诸如第一个成员之类的某些成员,并且您将该成员传递给snprintf 而不进行设置。

    编辑:我知道问题出在Interface 的第一个成员的原因是因为如果是其他内存,valgrind 会说类似Uninitialised value is 4 bytes into a block created by a heap allocation 而不仅仅是Uninitialised value was created by a heap allocation

    【讨论】:

    • 其实我的interfaces里有这个。c:351 char sql[300] = ""; snprintf(sql, sizeof (sql), "INSERT INTO interfaces (nome,endereco_ipv4,mac_address, ativa) VALUES ('%s','%s','%s','%s')", iface->interface_name, iface->interface_addr_ipv4, iface->interface_mac_addr, iface->interface_active == INTERFACE_ACTIVE ? "true" : "false");
    • 未初始化的值是Interface的第一个成员。见编辑。