Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

free of malloc inside the function, how to do that?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading