Working one step at a time from a working version, I found that replacing
char appnamestring [] = "appname_1.1";
with
char appnamestring [] = {"appname_1.1\0"};
makes it work.
Aha! I wager you are trying to append to an object in initialized data, without reserving enough room for the modified version.
If you are effectively doing
strcat(appnamestring, "\r\n"); (say via
char *p = get_appname(); strcat(p, "\r\n");), you are overwriting initialized data following the
appnamestring object!
If you have
const char appnamestring [] = "appname_1.1";then the object is stored in Flash, and if you do
char *p = get_appname(); strcat(p, "\r\n");you are effectively trying to modify Flash memory contents, which will obviously fail.
In practice, you should instead create a copy of the string, reserving enough memory for the modified string, and use that:
void foo() {
const char *name = get_appname();
const size_t namelen = (name) ? strlen(name) : 0;
// Temporary copy on stack
char modified[namelen + 2 + 1]; // +2 for "\r\n", +1 for final "\0"
#if 1
if (namelen > 0)
memcpy(modified, name, namelen);
modified[namelen + 0] = '\r';
modified[namelen + 1] = '\n';
modified[namelen + 2] = '\0';
#else
modified[0] = '\0';
if (namelen > 0)
strcat(modified, name);
strcat(modified, "\r\n");
#endif
//
// Do something with the 'modified' string
//
// Since 'modified' was on stack, it will not exist after we return from this function
}
Here, the temporary copy is on stack. The
#if 1 ... #else ... #endif shows the two ways to create the copy and append the CR-LF newline, but since it is just two fixed characters, I recommend using the first.
(The alternate method is to use a preprocessor macro containing the application name as a string, and reserve enough space for a suffix:
#define APPNAME "appname_1.1" char appnamestring[sizeof (APPNAME) + 4] = APPNAME;which initializes the array to the expected value, including a trailing null character (via
sizeof string-literal), plus reserves space for four more characters. That is, you can do
strcat(appnamestring, "abcd"); safely exactly once. Because this permanently changes the application name, I do not recommend doing this.)