I have some c++ piece of code that looks like this
StatusMessage foo() {
...
if(errorCondition) {
return StatusMessage("some custom error message");
} else {
return StatusMessage::OK;
}
}
The constructor of StatusMessage takes a const char* and stores the pointer of it.
Now I would like to return a formatted string, however.
I assume the following would likely lead to a crash since the memory of not_ok is only valid during the scope of this function.
StatusMessage foo() {
...
if(errorCondition) {
char not_ok[512];
sprintf(not_ok, "some custom error message with additional detail: %d", someInt);
return StatusMessage(not_ok);
} else {
return StatusMessage::OK;
}
}
Now, while I know the following is not clean and will overwrite the content of older StatusMessage values if the method is executed multiple times, I wonder if this is generally safe in terms of memory access (unless the message overflows the buffer):
StatusMessage foo() {
...
if(errorCondition) {
static char is_this_ok[512];
sprintf(is_this_ok, "some custom error message with additional detail: %d", someInt);
return StatusMessage(is_this_ok);
} else {
return StatusMessage::OK;
}
}
const char *as paramter? Does it copy that string or just store the pointer?StatusMessageclass stores just the pointer itself, then thestaticarray is fine. But note that technically you're not really storing a pointer to the array, but rather only a pointer to the first element (character) of the array.foo()at the same time