Don't use a static buffer unless you are sure you are never going to use this in multithreaded code, and that you'll never call it twice before using the first answer.
Malloc is an option, but forcing the caller to free the memory that a callee allocated can leave open issues of ownership and removes the possibility of using anything but heap memory for the buffer.
Your best bet, in my opinion, is to take a modification of Andrew Grant's suggest, but pass around the length of the buffer as well:
char *czas(char *buffer, size_t bufferLength)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime (buffer, bufferLength, "Now it's %I:%M%p.",timeinfo);
return buffer;
}
int main()
{
char buffer [80];
printf("%s",czas(buffer, sizeof(buffer)));
system("PAUSE");
}
Or
#define TIME_BUFFER_LENGTH 80
int main()
{
char *buffer = malloc(TIME_BUFFER_LENGTH);
if (buffer)
printf("%s",czas(buffer, TIME_BUFFER_LENGTH));
free(buffer);
system("PAUSE");
}
This makes it easier to keep track of potential memory leaks, and buffer overflows. You can look at czas
and see that as long at the arguments are correct, the function is not going to overflow any buffers, or leak any memory. Next, you can look at either version of main
and see that no memory is leaked, and that the parameters passed to czas are correct (the bufferLength parameter accurately specifies the amount of space that buffer points to.)