函数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()返回的指针,否则行为是未定义的.