alt alt - 1 year ago 112
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download