As another said, you are using data that is on the stack, and ceased to exist after you leave the function that declared it. I see two simple possibilities to solve this problem:
Option 1: allocate a buffer variable in the calling function and pass the pointer to get_timestamp
void get_timestamp( char *buffer, size_t buffersize ) { .... strftime (buffer,buffersize,"%G%m%d%H%M%S",timeinfo); } int main() { char buffer[16]; puts(get_timestamp(buffer,16)); return 0; }
Note. / Editing: I threw off a very true point about passing buffer size to this proposed solution.
Option 2: if you cannot or do not want to change the signature of your function, you can use a static variable, but do not forget that static variables can cause problems in multi-threaded programs.
static char buffer[16]; char* get_timestamp(){ ... } int main() { puts(get_timestamp()); return 0; }
Of course, you could use malloc , but in this situation this seems redundant and more error prone than the two fixes you described.
source share