2

I have this function:

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);
}

It seems to cause a memory leak. I think, that anyhow I'm not freeing mallocated memory. I don't know how can I fix this. Here output from 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)
MaMu
  • 1,837
  • 4
  • 20
  • 36
  • Whatever is calling `getCharVal()` is not freeing the (returned) dynamically allocated memory. Please show the code that calls `getCharVal()` for further information. – trojanfoe Jan 08 '14 at 17:03

1 Answers1

3

g_strndup allocates a new chunk of memory for the string and returns it. You must call g_free() on the returned pointer once you are done with it.

For example:

gchar *str = getCharVal(...);
/* use str */
g_free(str)
Kyle Lutz
  • 7,966
  • 2
  • 20
  • 23