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()
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.
The only chunks of memory that must be free
d are those that were previously malloc
ed.
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.
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.