我有这个功能:
char *getCharVal(const char *ch, const char *att, size_t size)
{
CHECK_NULL(ch);
CHECK_NULL(ch = strstr(ch, att));
ch += strlen(att);
char *end = strchr(ch, '"');
CHECK_NULL(end);
char *endTag = strstr(ch, ENDTAG);
CHECK_NULL (endTag);
if (end > endTag) {
return NULL;
}
size_t valSize = end - ch;
if (valSize > size) {
return NULL;
}
return g_strndup(ch, valSize);
}
它似乎导致内存泄漏。我想,无论如何我都没有释放mallocated内存。 我不知道如何解决这个问题。 这里输出来自valgrind:
==9556== 2,996 bytes in 428 blocks are definitely lost in loss record 272 of 301
==9556== at 0x4A21370: malloc (vg_replace_malloc.c:291)
==9556== by 0x4B5AA95: g_malloc (in /opt/gnome/lib64/libglib-2.0.so.0.800.6)
==9556== by 0x4B6CB48: g_strndup (in /opt/gnome/lib64/libglib-2.0.so.0.800.6)
==9556== by 0x402376: getCharVal (c2.c:244)
==9556== by 0x403381: processXML (c2.c:408)
==9556== by 0x4039C6: main (c2.c:558)
答案 0 :(得分:3)
g_strndup
为字符串分配一块新内存并返回它。完成后,必须在返回的指针上调用g_free()
。
例如:
gchar *str = getCharVal(...);
/* use str */
g_free(str)