不可重入函数localtime,
localtime函数实现的问题:
该函数返回的是一个指针,表示某一个地址。
大家知道,如果是一个非静态的局部变量,返回它的地址是错误的做法,因为非静态的局部变量在函数返回时,已经被销毁了,它的地址成为无用的地址。
因此localtime函数返回的指针只有以下三种可能:
要么是一个静态变量的地址,要么是一个全局变量的地址,或者是使用malloc等函数在堆上分配的空间。
对于最后一种情况,因为标准并没有规定可以对localtime返回的地址进行free,所以如果localtime函数是使用malloc函数分配空间的话,程序员不会使用free函数去释放它,因此造成内存泄露,这是不好的做法。
int main()
{
time_t tNow =time(NULL);
time_t tEnd = tNow + 3600;
struct tm* ptm = localtime(&tNow);
struct tm* ptmEnd = localtime(&tEnd);
char szTmp[100] = {0};
strftime(szTmp, 100, "%H:%M:%S",ptm);
char szEnd[100] = {0};
strftime(szEnd, 100, "%H:%M:%S",ptmEnd);
printf("%s\n", szTmp);
printf("%s\n", szEnd);
return 0;
}
结果:
00:39:24
00:39:24
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
time_t tNow = time(NULL);
time_t tEnd = tNow + 3600;
struct tm* ptm = localtime(&tNow);
char szTmp[100] = { 0 };
strftime(szTmp, 100, "%H:%M:%S", ptm);
struct tm* ptmEnd = localtime(&tEnd);
char szEnd[100] = { 0 };
strftime(szEnd, 100, "%H:%M:%S", ptmEnd);
printf("%s\n", szTmp);
printf("%s\n", szEnd);
return 0;
}
结果为:
23:40:37
00:40:37