C appending char to char*
Solution 1
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.
Solution 2
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).
Solution 3
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.
Man Person
Updated on July 09, 2022Comments
-
Man Person 6 monthsSo I'm trying to append a
charto achar*.For example I have
char *word = " ";I also havechar ch = 'x';I do
append(word, ch);Using this method..void append(char* s, char c) { int len = strlen(s); s[len] = c; s[len+1] = '\0'; }It gives me a segmentation fault, and I understand why I suppose. Because
s[len]is out of bounds. How do I make it so it works? I need to clear thechar*a lot as well, if I were to use something like char word[500]; How would I clear that once it has some characters appended to it? Would thestrlenof it always be500? Thanks in advance. -
Tom Tanner about 10 yearschar buf[len+2] might not compile, depending on the version of his compiler -
user1888162 over 5 yearsThis is bad answer because you don't know if *s contains string literals. They are usually stored in read only memory and that may result in access violation if you to modify them. Your code may work but it is considered as undefined behavior. -
djechlin over 5 years@user1888162 it's also UB if you pass in a large number for size. -
bomben about 1 yearI get: ‘append’ makes integer from pointer without a cast [-Werror=int-conversion] name, strlen(nickname), " ");