I need a char* composed by another char* and a String.
char* myFunction(){
String my_str = "sent";
char* chary = "message";
int str_len = my_str.length() + 1;
char buf[str_len];
my_str.toCharArray(buf, str_len);
strcat(chary, buf);
return chary;
}
PaulS:
It’s not undefined at all. The effect may be unexpected, but the behavior (of the compiler) is not undefined.
It is indeed undefined behavior. This is from the C++ 11 draft standard, section 2.14.5:
The effect of attempting to modify a string literal is undefined.
I don’t have a copy of the older C++ standards, but modifying a string literal has been undefined behavior since the days of C89 (the C++ standards borrow heavily from the C standards). This is from the C89 draft standard, section 3.1.4:
If the program attempts to modify a string literal of either form, the behavior is undefined.
(“either form” means either wide or non-wide.)
You can think of a string literal as being of type “const char *”, which obviously cannot be modified.
KeithRB:
Chistop: They are not writing to a string literal, they are writing to ca char array that is initialised to a string literal.
Nope. This declares chary to be a pointer to char and initializes it to point to a string literal:
char* chary = "message";
You cannot modify the contents of a string literal even through a non-const pointer to it. Besides, the compiler should give you a warning for that like “warning: deprecated conversion from string constant to ‘char*’”, which tells you that you’re probably doing something wrong (g++ version 4.7.4 does for me, even without -Wall).
On the other hand, this would initialize chary to be a string that you can modify: