ctime 函数实现疑惑
我们可以看到c函数库手册中其原型char *ctime(const time_t *time); 显然输入参数和函数返回值类型不一致,因此,这样函数返回值的字符串就不可能由输入参数指定这个字符串的空间地址
这样的话,我就有点疑问了,这个ctime函数返回值的字符串指针到底是一个全局变量呢?还只是一个静态变量呢?
显然这个字符串空间不会由malloc函数获取,否则空间无法释放会造成内存泄露
2010-07-04 04:02
程序代码:#include <stdio.h>
#include <time.h>
int main(void)
{
time_t t;
time(&t);
printf("Today's date and time: %s\n", ctime(&t));
printf("The string address 1 : %x\n", ctime(&t));
printf("The string address 2 : %x\n", ctime(&t));
return 0;
}上述代码执行结果显示这个地址值一致不变,更加确认这个字符串地址值不是malloc动态申请的
2010-07-04 04:05

2010-07-04 04:40

2010-07-04 09:58
程序代码:/* 这里的函数在GNU libc的locale/C-time.c中定义 */
#include <stdio.h>
#include <time.h>
extern const struct locale_data _nl_C_LC_TIME attribute_hidden;
#define ab_day_name(DAY) (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (ABDAY_1)+(DAY)].string)
#define ab_month_name(MON) (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (ABMON_1)+(MON)].string)
static const char format[] = "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n";
static char result[ 3+1+3+1+20+1+20+1+20+1+20+1+20+1+1];
static char * asctime_internal (const struct tm *tp, char *buf, size_t buflen)
{
if (tp == NULL)
{
__set_errno (EINVAL);
return NULL;
}
if (__builtin_expect (tp->tm_year > INT_MAX - 1900, 0))
{
eoverflow:
__set_errno (EOVERFLOW);
return NULL;
}
int n = __snprintf (buf, buflen, format,
(tp->tm_wday < 0 || tp->tm_wday >= 7 ?
"???" : ab_day_name (tp->tm_wday)),
(tp->tm_mon < 0 || tp->tm_mon >= 12 ?
"???" : ab_month_name (tp->tm_mon)),
tp->tm_mday, tp->tm_hour, tp->tm_min,
tp->tm_sec, 1900 + tp->tm_year);
if (n < 0)
return NULL;
if (n >= buflen)
goto eoverflow;
return buf;
}
char * __asctime_r (const struct tm *tp, char *buf)
{
return asctime_internal (tp, buf, 26);
}
weak_alias (__asctime_r, asctime_r)
char * asctime (const struct tm *tp)
{
return asctime_internal (tp, result, sizeof (result));
}
libc_hidden_def (asctime)
char * ctime (const time_t *t)
{
return asctime (localtime (t));
}
2010-07-04 13:09

2010-07-04 16:59
2010-07-04 17:21