How do I know when I ought to free strings in C re

2019-07-14 12:11发布

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()

3条回答
Lonely孤独者°
2楼-- · 2019-07-14 12:30

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-14 12:39

The only chunks of memory that must be freed are those that were previously malloced.

Now the questions are "is this pointer a pointer to memory that was created by malloc ?" and, if so, "am I supposed to free it myself or will some other function take care of it ?"

There are no easy answers to these questions, generally the documentation will tell you so, but the rule of thumb is that the module that takes care of memory creation also takes care of deallocation. So, if the library you use expects you to provide already allocated memory, you are supposed to free it, too, when needed.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-07-14 12:56

In case of explicit dynamic allocation i.e. malloc/alloc/realloc you have to explicitly free it. But now that you have mentioned about strings there is a special function strdup() which under-the-hood malloc for you when you call it.

In case of strdup(), you have to make sure that without you allocating you MUST free it.

查看更多
登录 后发表回答