Home > database >  Free a char* that was malloc'd by a function
Free a char* that was malloc'd by a function

Time:01-23

#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).

CodePudding user response:

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
}

CodePudding user response:

Theory:

Every heap allocated object should be freed, before exiting the application (most of the modern operating system manages the heap allocation even if you didn't freed them at exiting the application). By the way freeing heap resources is a good practice though.

Problems in your code:

  1. Parameters for mkstr function should be (const char *str1, const char *str2) instead of (char str[], char str2[]).
  2. Use calloc instead of malloc for better safety.
  3. Use strlen function to determine the length of the string, instead of sizeof.
  4. Set void or (int argc, char const **argv) as the parameter of main function.

Now `free` heap allocations:

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

char *mkstr(const char *str1, const char *str2)
{
    char *out = calloc(sizeof(char) * (strlen(str1)   strlen(str2)   1), sizeof(char));
    strcpy(out, str1);
    strcat(out, str2);
    return out;
}

int main(int argc, char const **argv)
{
    char *str = mkstr("i use ", "arch btw");
    printf("%s\n", str);
    free(str); // freed the heap allocated resource before exiting
    return 0;
}

CodePudding user response:

Anyways, after reading all your answers, this is the new code.

char* mkstr(char str1[], char str2[])
{
        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);

        return 0;
}
  •  Tags:  
  • Related