Using GDB, I find I get a segmentation fault when I attempt this operation:
strcat(string,¤tChar);
Given that string is initialized as
char * string = "";
and currentChar is
char currentChar = 'B';
Why does this result in a segmentation fault?
If strcat can't be used for this, how else can I concat a char onto a string?
As responded by others, ¤tChar is a pointer to char or char*, but a string in C is char[] or const char*.
One way to use strcat to concatenate a char to string is creating a minimum string and use it to transform a char into string.
Example:
Making a simple string, with only 1 character and the suffix '\0';
Applying to your question:
cToStr will assume the string "B":
And strcat will work!
Because
¤tChar
is not a string, it doesn't finish with\0
character. You should defineB
aschar *currentChar = 'B';
. Also according to http://www.cplusplus.com/reference/clibrary/cstring/strcatstring
should have enough space to hold the result string (2 bytes in this case), but it is only 1 byte.Or if you want to use
char
then you can do something like (depending of your code):Both of the strings must be null-terminated. A single char isn't null terminated, so it's undefined when strcat will stop concatenating characters to the end. Also, string must contain at least enough space for both the original string and resultant string.
This works:
The first argument of strcat must have enough space to hold the rest of the string. "" is a constant string and as such GCC does not allocate space.
Make it an array with enough space:
I think the simplest method (not efficient) would be
sprintf
sprintf(str, "%s%c", str, chr);
strcat() takes two '\0'-terminated strings. When you pass the address of a character, the routine will look at the memory that follows the character, looking for the terminator.
Since you don't know what that memory even refers to, you should expect problems when your code accesses it.
In addition to that, your string argument does not have room to have any characters appended to it. Where is that memory written to? It will attempt to write past the end of the memory associated with this string.