#include <stdio.h>
#include <alloca.h>
#include <time.h>
// crappy example
char *new_ctime_r(const time_t * timep, char *buf, int buflen)
{
if (buflen < 26)
return NULL;
return ctime_r(timep, buf);
}
// function called in a multi-threaded application
void printtime()
{
int buflen = 0;
char *ptr, *output;
time_t t;
t = time(NULL);
// ctime converts a time_t value to string
// ctime_r is the re-entrant version of ctime
do {
buflen = buflen * 2 + 1;
output = alloca(buflen);
}
while ((ptr = new_ctime_r(&t, output, buflen)) == NULL);
printf("%d bytes was allocated at %p\n", buflen, output);
printf("The datetime is %s", ptr);
}
int main()
{
printtime();
return 0;
}