No, of course you can't free memory that belongs to the data you're returning. And indeed allocating memory within a utility function like this makes memory leaks extremely likely; since the caller won't see the function body, it will be very easy for her to forget to free it. There is a standard solution to this issue actually, and that is to make the caller allocate the memory himself:
void fakeTrim(const char* input, char* temp) {
int count = 0;
for(int i = 0; i < strlen(input); i++) {
if(input[i] != ' ')
temp[count++] = input[i];
}
temp[count] = '\0';
}
Now memory leaks are still possible but it's not 'your fault'--the caller should know to free memory that he allocates. Note the addition of const
in the signature makes which argument is input, and which is output, clear.
Edit: Here's a use case:
const char* input = "Hello world";
char* temp = malloc(strlen(input)+1);
fakeTrim(input, temp);
// ... do something with temp
free(temp);