I am working on a custom SD card data logger using the following function and struct:
char *filenameCreator(const char *prefix, const char *num, bool addExtension)
{
char *filename = (char *)malloc(13 * sizeof(char));
const char *uScore = "_";
strcpy(filename, prefix);
strcat(filename, uScore);
strcat(filename, num);
if (addExtension)
{
const char *ext = LOGFILE_EXTENSION;
strcat(filename, ext);
}
delete[] num;
return filename;
}
where the output will be saved on a variable of the following type:
struct FileInfo
{
const char *fileName;
double fileSize;
};
with FileInfo fileToDelete;
and a global variable
char* createdFilename = nullptr;
to temporarily store the function's output.
The issue is that when using the functions as follows, fileToDelete.fileName
is EMPTY:
createdFilename= filenameCreator("FILE", numericConverter(receivedIndexSATCOM), true);
fileToDelete.fileName = createdFilename;
free(createdFilename); // seems to clear the contents of the variable where the filename was stored, namely, fileToDelete.fileName
createdFilename = nullptr;
I am trying to stick to the rules of freeing up memory used by malloc'd
variables.
Please note that if I DON'T USE free(createdFilename)
, the code works fine and the fileName is created correctly. However, I am concerned about undefined behaviour or erratic responses.
Here is an example of a filename successfully created when NOT using free():
Do I invariably need to free the pointer after each use? Why the contents are empty even after assigning the contents to another variable?
EDIT:
Please, instead of downvoting my question, comment on what is wrong with my questions and I will try to improve it. Be mature.