tm*释放问题(关于localtime、gmtime易出错的知识点)

使用gmtime方法时,对返回值tm*做了释放处理,出现错误:

int UnixTime2TimeId(time_t &stampTime)
{
    tm *pTm = gmtime(&stampTime);
    int timeId(0);
    timeId = (int)((pTm->tm_hour * 3600 + pTm->tm_min * 60 + pTm->tm_sec) / 30);
    if (timeId == 0)
	timeId = 24 * 3600 / 30;
    delete pTm;
    pTm = NULL;
    return timeId;
}

查阅gmtime文档,Return Value介绍:

The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime.

localtime、gmtime函数返回的指针无需释放,下一次调用该函数时,其有效性(值)会被改变。

无需担心内存泄漏,删掉两行代码即可:

int UnixTime2TimeId(time_t &stampTime)
{
    tm *pTm = gmtime(&stampTime);
    int timeId(0);
    timeId = (int)((pTm->tm_hour * 3600 + pTm->tm_min * 60 + pTm->tm_sec) / 30);
    if (timeId == 0)
	timeId = 24 * 3600 / 30;
    return timeId;
}

你可能感兴趣的:(C++,c++)