I have a function which takes a const char* and adds a number to it:
const char* CheckName(const char* name, int number) {
std::string s = std::to_string(number);
std::string s1(name);
const char* c = (s1 s).c_str();
return c;
}
But this function only returns rubbish, because the pointer c is dangling. Is there any way that I can rewrite that function? Thanks in advance.
CodePudding user response:
s1 1
(being a temporary) goes out of scope at the end of the statement that uses it. c
is therefore left dangling, event before you return from CheckName
.
There is no safe way to return a const char *
from this function. Return a std::string
instead (which should not be declared const
).
CodePudding user response:
The problem of this function, as you suspect, is that it returns a pointer to an invalid location. That is because you return the pointer internally kept in your (s1 s)
string which, being declared inside the function, goes out of scope as soon as the function returns and its data is no longer valid.
The best solution is what Paul Sanders suggests, which is returning a string:
std::string CheckName(const char* name, int number) {
return std::string(name) std::to_string(number);
}
If you need to keep the pointer-based function, the solution is to adopt a C-style approach as in
void CheckName(char* result, const char* name, int number) {
std::string result_str = std::string(name) std::to_string(number);
std::memcpy(result, result_str.c_str(), result_str.size());
}
This forces you to declare the result
array in the caller function, meaning you should know its size (or an upper bound to the size) beforehand.
If you can't know the result size beforehand and still need to use pointers, your other solution would be to allocate with new
inside CheckName()
, but that is dangerous/bad territory and I would suggest against it.