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

时光毁灭记忆、已成空白 提交于 2019-12-24 04:56:12

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/43187986/how-do-i-know-when-i-ought-to-free-strings-in-c-returned-by-library-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!