return string with persistence buffer

Sunday, May 4, 2014

I tried to write a function that formats a value into string. However, i encounter issue with its persistence.

using namespace std;

string string_format(const string &msg, ...)
va_list ap;
char text[BUFF_SIZE] = { 0, };
va_start(ap, msg);
vsnprintf(text, BUFF_SIZE - 1, msg.c_str(), ap);
text[BUFF_SIZE - 1] = '\0';

return string(text);

int main()
char* p1 = (char*)string_format("%d", 123).c_str();
char* p2 = (char*)string_format("%d", 45).c_str();

printf("value: p1=%s, p2=%s\r\n", p1, p2);

The above will print:

value: p1=45, p2=45

instead of

value: p1=123, p2=45

I wrote the code this way because i want to keep 2 or more string instance at the same time. return "new string(text)" works, but i dont want to keep writing "delete"