I want to concatenate two strings using a function that returns the resulting string. it would be something like this:
char *String_Concat (char *String_1, char *String_2)
{
char *StringResult;
//memmove String_1 to StringResult
//memmove String_2 to StringResult
return StringResult;
}
I wonder if that is a good way of doing that, since I know little about memory management. StringResult does not have a defined length, and I am not sure what will happen after two memmove operations.
I suppose StringResult will be cleaned up by the function itself, since I do not use malloc(), correct?
char *String_Concat (char *String_1, char *String_2)
{
size_t len1 = strlen(String_1);
size_t len2 = strlen(String_2);
char *StringResult = malloc(len1+len2+1);
//might want to check for malloc-error...
memcpy(StringResult, String_1, len1);
memcpy(&StringResult[len1], String_2, len2+1);
return StringResult;
}
So, C has the concept of storage
for objects. The storage of an object determines its lifetime, as C is not garbage-collected. If you want to create a new string, You must reserve storage for it. The easiest way would be automatic storage, but that is associated with the scope of the function it is declared in, so automatic variables cease to exist after function return. Alternatively, you could use static storage, but that cannot be of variable size, and multiple calls to the function would use the same storage. Finally, you can use allocated storage, which requires malloc()/calloc()/realloc()/free()
.
See C11 draft standard, section 6.2.4 Storage durations of objects