函数ctime
的原型(prototype)是
char *ctime(const time_t *timep);
正如我们所见,它返回一个字符串。但是,毒刺在哪里?
为什么我们不应该释放字符串的内存
这是示例代码,会收到很多错误消息
char *p;
p = ctime(...);
...
free(p);
*** 检测到 glibc *** ./a.out: free(): 无效指针:0x00007f0b365b4e60 ***
最佳答案
它返回一个指向static
缓冲区的指针,并且不能是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 The ctime function 声明调用 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()
,否则行为未定义。
关于ctime() 返回一个字符串,为什么我们不需要 free() 这个字符串的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11257774/