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 a char* that was malloc'd by a function

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* mkstr(char str1[], char str2[])
{
        char* out = malloc(sizeof(*str1) + sizeof(*str2) + 1);
        strcpy(out, str1);
        strcat(out, str2);

        return out;
}

int main()
{
        char* str = mkstr("i use ","arch btw");
        printf("%s\n",str);
}

When main() calls mkstr(), mkstr() will malloc a char* called out. How can I free(out) properly from this code? Can I just leave it be, or will the OS just free up the malloc’d space?

Is this the best way to do it, or are there better ways of doing it?

I’m on Linux (if that’s relevant).

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

>Solution :

sizeof(*x) is the size of a pointer on your platform. It’s usually 4 on a 32 bit platform and 8 on a 64 bit platform.

To get the length of a string you need to use the strlen function.

Corrected code:

char* mkstr(char str1[], char str2[])
{
        // you need to use strlen to get the length of a string
        char* out = malloc(strlen(str1) + strlen(str2) + 1);

        strcpy(out, str1);
        strcat(out, str2);
        return out;
}

int main()
{
        char* str = mkstr("i use ","arch btw");
        printf("%s\n",str);
        free(str);           // simply free str
}
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