matthias_buehlmann
matthias_buehlmann

Reputation: 5061

c++ is it valid to return pointer to static array defined inside function?

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;
  }
}

Upvotes: 4

Views: 162

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

This will work, and it is safe, but every instance of StatusMessage you create here will share the same string, so it will lead to messy code no one wants to deal with. A better thing to do is to copy the string in StatusMessage constructor. Use a std::string to manage the memory and it should work flawlessly.

If you can't change the code in StatusMessage, the solution you got there may be good enough. It depends on what you want to do. Another option is creating a wrapper class of some sort.

Upvotes: 6

Related Questions