#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).
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
}
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.
mkstr
function should be (const char *str1, const char *str2)
instead of (char str[], char str2[])
. calloc
instead of malloc
for better safety.strlen
function to determine the length of the string, instead of sizeof
.void
or (int argc, char const **argv)
as the parameter of main
function.#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;
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.