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