简体   繁体   中英

C function using strcat with strings

I'm trying to learn C. So I've challenged myself to create a function called two() which will effectively "double" a string.

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

But I'm having trouble using strcat() 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 strcat with pointer strings.

There are multiple rules of strcat you are breaking:

  • The first parameter shouldn't be a string literal, because it's non-modifiable.
  • The first parameter must be large enough for the concatenated string.
  • The first and second parameter shouldn't overlap.

The docs say strcat

Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.\\

You're passing a constant string "foo" to strcat as the destination buffer. Trying to overwrite constant string is bad. Even if it weren't constant, you're writing 7 characters over 4 (including the terminating nulls). This is also bad.

You probably want this:

char *two(char *result, char *str)
{
    return strcat(strcpy(result, str), str);
}

And when you call it,

int main() {
    char buf[40];
    printf("The value of two(\"foo\") is %s", two(buf, "foo"));
}

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);
    free(ptr);
}

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

It seems you are misunderstanding strcat . Have a look at this link for a brief explanation of what it does. In particular the man page says that

The strings may not overlap, and the dest string must have enough space for the result

You are passing it the same address for both parameters, which means that the strings overlap . Also, I can't see how you are allocating the string so I can't tell if there is enough space in the buffer / array for the resulting string.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM