I review the following code (simplified) and ask myself how safe it is to use this returnMsg function:
#include <iostream> using namespace std; const char *returnMsg(const char *msg) { static std::string message; message = msg; return message.c_str(); } int main(int argc, char *argv[]) { const char *msg1 = returnMsg("Hello world"); printf("msg1 = %p\n", msg1); cout << msg1 << endl; const char *msg2 = returnMsg("Good bye"); printf("msg2 = %p\n", msg2); cout << msg2 << endl; cout << msg1 << endl; return 0; }
output:
msg1 = 0x23a6028 Hello world msg2 = 0x23a6028 Good bye Good bye
msg2 written twice, and this is what I expected, since the static message variable remains in memory during the program life cycle and there is no memory reallocation, therefore, what is written at msg1 is replaced with new msg2 content.
However, if msg2 larger, there is an internal redistribution inside the variable std::string message , and the output is:
msg1 = 0x1cc6028 Hello world msg2 = 0x1cc6058 Good bye looooooooooooooooooooooooooooooooooooooooong Hello world
but I think there is no guarantee that msg1 will not be reused in the future, and therefore new access to msg1 content may ultimately display something else and not consistent.
Does this function need to be written in different ways so that it can be used without the restrictions mentioned above?
c ++
Scab
source share