Say I have the function below :
char* fakeTrim(char* input) {
char* temp = malloc(strlen(input));
int count = 0;
for(int i = 0; i < strlen(input); i++) {
if(input[i] != ' ')
temp[count++] = input[i];
}
temp[count] = '\0';
return temp;
}
Does the temp cause any memory leakage? IF so, is it possible to free it before we return temp?
Thanks!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With