Defined in h file:
char *copiedText;
Defined in c file:
char *copyText(char *text){
if (copiedText != 0) free(copiedText);
copiedText = (char *)calloc((strlen(text) + 1) * sizeof(char), sizeof(char));
strcpy(copiedText, text);
return copiedText;
}
First off, this isn't about how to copy text, I just chose that as an example. My question is about the free() before calloc().
First question I hear you ask is why not just free() at the appropriate time - i.e. when copiedText is no longer needed?
Long story short, I'm making part of a program and I can not trust the users of my function to properly free() copiedText, so I want to contain as much code inside my function as possible. All they do is include h and c file and call the function copyText.
I am aware there will be a (minor) memory leak between last call to copyText and program termination, but this is a tradeoff that I am willing to accept, because I only malloc() small amounts of data.
The question is simply, will the free() actually free up the memory allocated by my calloc() when coded like this?