I am currently trying to convert an existing MATLAB project into C code using MATLAB Coder, and have been using the guidance provided here to write and call C implementations for unsupported functions, such as fullfile. The article linked shows how to have matlab check whether we are running in MATLAB or not to decide whether to run the C file or just use the MATLAB built-in function.
I created a basic implementation of fullfile in C, but since I will not know the string sizes until runtime, the character array for the return values is dynamically allocated with malloc. The problem is, I expect this will result in a memory leak, since the return value is never freed. However, I'm not certain how I can instruct MATLAB Coder to free that allocated char array once it's done being used. Will this cause a memory leak? If so, how can I prevent it from happening by properly freeing allocated memory while still providing the return value?
My c-implementation of fullfile is copied below:
This simplified implementation of fullfile simply concatenates two strings with a '/' inbetween.
For example, fullfile_impl("/home/user", "mydir") would output "/home/user/mydir".
char * fullfile_impl(char *a, char *b)
int length = strlen(a) + strlen(b) + 1;
char* returnString = malloc(length);
*returnString = *a;
*returnString = '/';
*returnString = *b;
*returnString = '\0';
returnString -= (length);