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?
The flip side is that now:
copyText()is only valid until the next call tocopyText()— this is not at all obvious to the caller and is probably worth documenting as prominently as you can;A better approach might be to require an explicit
free()(perhaps wrapping it in a function calledfreeText(), as a counterpart tocopyText()).Another alternative is for the caller to provide their own buffer along with its size (so that you can avoid buffer overruns).