alt alt - 1 month ago 5x
C Question

C function using strcat with strings

I'm trying to learn C. So I've challenged myself to create a function called

which will effectively "double" a string.

two("foo") // => "foofoo"

But I'm having trouble using
in conjunction with pointers. Here's what I have:

char *two(char *foo);

int main() {
printf("The value of two(\"foo\") is %s", two("foo"));

char *two(char *foo) {
return strcat(foo, foo);

It compiles but errors on run. Why?

I have a feeling the error resides in using
with pointer strings.


You didn't allocate space to hold two copies of your input string.

strcpy copies strings.

strcat appends one string onto another.

malloc allocats bytes on the heap that should be free() later.

char *two(char *foo);

int main() {
    char * ptr =  two("foo");
    printf("The value of two(\"foo\") is %s", ptr);

char *two(char *foo) {
    char * ptr = malloc(strlen(foo) * 2 + 1);
    strcpy(ptr, foo);
    strcat(ptr, foo);
    return ptr;