localtime 问题



不可重入函数localtime,

localtime函数实现的问题:
该函数返回的是一个指针,表示某一个地址。

大家知道,如果是一个非静态的局部变量,返回它的地址是错误的做法,因为非静态的局部变量在函数返回时,已经被销毁了,它的地址成为无用的地址。

因此localtime函数返回的指针只有以下三种可能:
要么是一个静态变量的地址,要么是一个全局变量的地址,或者是使用malloc等函数在堆上分配的空间。
对于最后一种情况,因为标准并没有规定可以对localtime返回的地址进行free,所以如果localtime函数是使用malloc函数分配空间的话,程序员不会使用free函数去释放它,因此造成内存泄露,这是不好的做法。


int main()

{  

    time_t tNow =time(NULL);  

    time_t tEnd = tNow + 3600;  

  

    struct tmptm = localtime(&tNow);  

    struct tmptmEnd = 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 tmptm = localtime(&tNow);

    char szTmp[100] = { 0 };

    strftime(szTmp, 100, "%H:%M:%S"ptm);

 

    struct tmptmEnd = 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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值