How do I free memory dynamically allocated in a C function for use with MATLAB Coder?

9 views (last 30 days)
Paul Ammer
Paul Ammer on 20 Mar 2020
Answered: Aghamarsh Varanasi on 23 Mar 2020
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:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
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);
return returnString;

Answers (1)

Aghamarsh Varanasi
Aghamarsh Varanasi on 23 Mar 2020
I understand that you are using MATALB Coder to generate MATLAB equivalent C code. According to my understanding, MATLAB coder automatically frees the memory while using dynamic memory as soon as it is not in use. When calling a function with dynamic memory allocation, the memory can be freed after the execution of the function call. Hence memory leak might not take place.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!