C appending char to char*

前端 未结 5 1002
一个人的身影
一个人的身影 2021-01-18 06:15

So I\'m trying to append a char to a char*.

For example I have char *word = \" \"; I also have char ch = \'x\';

5条回答
  •  情深已故
    2021-01-18 06:37

    Yes, the assumption you made is - almost - correct - the crash may be because you're trying to write past the bounds of the string (actually only s[strlen(s) + 1] is out of bounds, because s[strlen(s)] is still a valid location - the terminating NUL byte is stored there). But you also can't modify a string literal, because it's usually in some readonly part of the process memory. Both of these actions lead to invocation of undefined behavior, which have the potential of crashing. You can solve this problem by copying the string to a dynamically allocated storage then modifying the copy. Also, you're supposed to use const char * in the argument of your function, because char * suggests that read-only strings can't be passed in.

    char *append(const char *orig, char c)
    {
        size_t sz = strlen(orig);
        char *str = malloc(sz + 2);
        strcpy(str, orig);
        str[sz] = c;
        str[sz + 1] = '\0';
        return str;
    }
    

    Also, don't forget to free() the returned string when it's not needed anymore.

提交回复
热议问题