我使用GLib的指针数组写了一个玩具函数:
#include <glib-2.0/glib.h>
#include <stdio.h>
void append_string(GArray* arr) {
g_array_append_vals(arr, "foo", 1);
}
int main() {
GPtrArray *arr = g_ptr_array_new();
append_string((GArray*)arr);
g_ptr_array_free(arr, TRUE);
return 0;
}
但是,使用valgrind运行它会产生:
==5876== Memcheck, a memory error detector
==5876== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5876== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==5876== Command: ./demo
==5876==
==5876== Conditional jump or move depends on uninitialised value(s)
==5876== at 0x4E532E9: ??? (in /usr/lib/libglib-2.0.so.0.4800.0)
==5876== by 0x4E536A7: g_array_append_vals (in /usr/lib/libglib-2.0.so.0.4800.0)
==5876== by 0x400727: append_string (main_arrays.c:5)
==5876== by 0x400747: main (main_arrays.c:11)
==5876==
==5876== Conditional jump or move depends on uninitialised value(s)
==5876== at 0x4E532EE: ??? (in /usr/lib/libglib-2.0.so.0.4800.0)
==5876== by 0x4E536A7: g_array_append_vals (in /usr/lib/libglib-2.0.so.0.4800.0)
==5876== by 0x400727: append_string (main_arrays.c:5)
==5876== by 0x400747: main (main_arrays.c:11)
==5876==
==5876== Conditional jump or move depends on uninitialised value(s)
==5876== at 0x4E536C9: g_array_append_vals (in /usr/lib/libglib-2.0.so.0.4800.0)
==5876== by 0x400727: append_string (main_arrays.c:5)
==5876== by 0x400747: main (main_arrays.c:11)
==5876==
==5876==
==5876== HEAP SUMMARY:
==5876== in use at exit: 18,604 bytes in 6 blocks
==5876== total heap usage: 8 allocs, 2 frees, 18,652 bytes allocated
==5876==
==5876== LEAK SUMMARY:
==5876== definitely lost: 0 bytes in 0 blocks
==5876== indirectly lost: 0 bytes in 0 blocks
==5876== possibly lost: 0 bytes in 0 blocks
==5876== still reachable: 18,604 bytes in 6 blocks
==5876== suppressed: 0 bytes in 0 blocks
==5876== Rerun with --leak-check=full to see details of leaked memory
==5876==
==5876== For counts of detected and suppressed errors, rerun with: -v
==5876== Use --track-origins=yes to see where uninitialised values come from
==5876== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
我是否滥用了API,这是GLib中的错误,还是valgrind错了?如果它是一个valgrind限制,我可以沉默这个valgrind警告,同时仍然让valgrind警告我的代码中的真正问题吗?
答案 0 :(得分:3)
GArray
和GPtrArray
不相同。这里没有子类型,即使它们有相同的公共字段。
改为使用g_ptr_array_add
:
void append_string(GPtrArray* arr) {
g_ptr_array_add(arr, "foo");
}