C appending char to char*

前端 未结 5 964
一个人的身影
一个人的身影 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:25

    If you're passing in

    append("foo", 'X');
    

    it will crash, because foo is normally put in readonly storage. Even if it isn't it will overwrite something bad probably! In this case the compiler if it's kind should warn you of conversion from const char * to char * which would be a clue.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 06:45

    Typical C practice would be like:

    //returns 1 if failed, 0 if succeeded 
    int  append(char*s, size_t size, char c) {
         if(strlen(s) + 1 >= size) {
              return 1;
         }
         int len = strlen(s);
         s[len] = c;
         s[len+1] = '\0';
         return 0;
    }
    

    When passing a function an array to modify the function has no idea at compile time how much space it has. Usual practice in C is to also pass the length of the array, and the function will trust this bound and fail if it can't do its work in the space it has. Another option is to reallocate and return the new array, you would need to return char* or take char** as an input but you must think carefully of how to manage heap memory in this situation. But without reallocating, yes, your function must somehow fail if it is asked to append when there is no space left, it's up for you for how to fail.

    0 讨论(0)
  • 2021-01-18 06:47

    You can't really safely append to an arbitrary string, because firstly, string constants tend to be in read-only memory, so trying to write to them is likely to result in a segmentation fault, and secondly, you have no guarantee that if they've passed you a buffer that you haven't shot over the end of it.

    In particular, if you do char x[500];

    there's no guarantee that strlen(x) will return you 500. It will return you how many characters it has to count forward from the start of x before it reaches a null. It could return you 0, 1 ... 500, 501 ..., depending on what is in x.

    Really your only options are to call append with the size of the buffer you are appending to (so you can do something appropriate if the buffer is full), or to make append allocate a new buffer every time it is called, in which case you will need to free the buffer again of course.

    0 讨论(0)
  • 2021-01-18 06:50

    It is hard to append to a string in-place in C. Try something like this:

    char *append(const char *s, char c) {
        int len = strlen(s);
        char buf[len+2];
        strcpy(buf, s);
        buf[len] = c;
        buf[len + 1] = 0;
        return strdup(buf);
    }
    

    Be sure to deallocate the returned string when done with it.

    FYI: It segfaults probably because the string you are passing is stored in read-only memory. But you're right, you are also writing off of the end (the [len+1] write, not the [len] one).

    0 讨论(0)
提交回复
热议问题