Search code examples
cstringmemory-leaksfreeallocation

How do I know when I ought to free strings in C returned by library functions?


Which strings ought I to free in C on my own, using free()¹?

My state of knowledge:

  • char a[256];: no
  • char *a = "abcdefg";: no
  • char *a = malloc(15L);: yes
  • a string returned by getenv(): no
  • strings returned by Windows functions²: ???

¹ or LocalFree()/GlobalFree()/VirtualFree()
² in particular by GetCommandLineW()


Solution

  • This will always be mentioned in the documentation for any API you use that returns strings (or other data larger than a single simple value such as an integer).

    Yes, this means you have to read the documentation thoroughly for all such API functions, in order to keep track and not leak memory.