微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ctime()返回一个字符串,为什么我们不需要free()这个字符串的内存?

函数ctime的原型是
char *ctime(const time_t *timep);

我们可以看到,它返回一个字符串.但是,哪里有刺痛?

为什么我们不应该释放字符串的内存

这是示例代码将获得大量错误消息

char *p;
p = ctime(...);
...
free(p);

*** glibc检测到*** ./a.out:free():指针无效:0x00007f0b365b4e60 ***

解决方法

它返回一个指向静态缓冲区的指针,并且不能是free()d.从 man ctime开始:

The four functions asctime(),ctime(),gmtime() and localtime() return a pointer to static data and hence are not thread-safe.

C99标准,第7.23.3.2节ctime函数声明调用ctime(timer)函数等同于asctime(localtime(timer)),而asctime()实现(如同一文档中所示)等效于:

char *asctime(const struct tm *timeptr)
{
    static const char wday_name[7][3] = {
        "Sun","Mon","Tue","Wed","Thu","Fri","Sat"
    };

    static const char mon_name[12][3] = {
        "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
    };

    static char result[26];
    sprintf(result,"%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",wday_name[timeptr->tm_wday],mon_name[timeptr->tm_mon],timeptr->tm_mday,timeptr->tm_hour,timeptr->tm_min,timeptr->tm_sec,1900 + timeptr->tm_year);

    return result;
}

传递给free()的参数必须是仅通过调用malloc(),calloc()或realloc()返回的指针,否则行为是未定义的.

原文地址:https://www.jb51.cc/c/110762.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐