I create the malloc inside str function and i want to free this malloc variable
#include <stdio.h>
char *str(void)
{
// create the malloc
char *string = malloc(2); // how to free it
*(string + 0) = 'J';
*(string + 1) = 'O';
// return the malloc
return string;
}
int main(void)
{
// print the function
printf("%s, str());
return 0;
}
>Solution :
free(string)
would free it. But to print it as a string you must have the \0 in the end.
Note: You should not free it inside the function if your plan is to return it at the end of the function call. Since that would potentially give rise to undefined behavior.
Correct way of doing things:
char *str(void)
{
// create the malloc
char *string = malloc(3); // how to free it
if(string){
*(string + 0) = 'J';
*(string + 1) = 'O';
*(string + 2) = '\0';
// return the malloc
}
return string;
}
int main(void)
{
// print the function
char *s = str();
if(s)
printf("%s", s);
free(s);
return 0;
}
Incorrect
If you do this, then it would be a memory leak:
int main(void)
{
// print the function
printf("%s", str());
return 0;
}
And if you do this, then you have undefined behavior when you try to print it out.
char *str(void)
{
// create the malloc
char *string = malloc(2); // how to free it
*(string + 0) = 'J';
*(string + 1) = 'O';
// return the malloc
free(string);
return string;
}
int main(void)
{
// print the function
printf("%s", str()); // undefined behavior. A dragon might appear.
return 0;
}