void main( void )
{
        struct tm *newtime;
        char am_pm[] = "AM";
        time_t long_time;        time( &long_time );                /* Get time as long integer. */
        newtime = localtime( &long_time ); /* Convert to local time. */        if( newtime->tm_hour > 12 )        /* Set up extension. */
                strcpy( am_pm, "PM" );
        if( newtime->tm_hour > 12 )        /* Convert from 24-hour */
                newtime->tm_hour -= 12;    /*   to 12-hour clock.  */
        if( newtime->tm_hour == 0 )        /*Set hour to 12 if midnight.*/
                newtime->tm_hour = 12;        printf( "%.19s %s\n", asctime( newtime ), am_pm );
}
我要问的是,localtime函数是如何为newtime分配的内存?为什么没有释放掉?localtime函数是怎么实现的?

解决方案 »

  1.   

    struct tm {
            int tm_sec;     /* seconds after the minute - [0,59] */
            int tm_min;     /* minutes after the hour - [0,59] */
            int tm_hour;    /* hours since midnight - [0,23] */
            int tm_mday;    /* day of the month - [1,31] */
            int tm_mon;     /* months since January - [0,11] */
            int tm_year;    /* years since 1900 */
            int tm_wday;    /* days since Sunday - [0,6] */
            int tm_yday;    /* days since January 1 - [0,365] */
            int tm_isdst;   /* daylight savings time flag */
            };
    它是如何把time_t(long)转换的成这个结构的?
      

  2.   

    Example/* ASCTIME.C: This program places the system time
     * in the long integer aclock, translates it into the
     * structure newtime and then converts it to string
     * form for output, using the asctime function.
     */#include <time.h>
    #include <stdio.h>struct tm *newtime;
    time_t aclock;void main( void )
    {
       time( &aclock );                 /* Get time in seconds */   newtime = localtime( &aclock );  /* Convert time to struct */
                                        /* tm form */   /* Print local time as a string */
       printf( "The current date and time are: %s", asctime( newtime ) );
    }
      

  3.   

    我不明白的是localtime函数是如何返回struct tm*的
    如果是这样子:
    struct tm* localtime(time_t time)
    {
         struct tm a;
         …………
         return &a;
    }
    a在“}”后就超出范围失效了啊,返回一个它的地址的话总觉得不大安全如果是这样子
    struct tm* localtime(time_t time)
    {
         struct tm *p=new struct tm;
         …………
         return p;
    }
    但在外面并没有释放函数里面new的东西,势必会造成内存泄漏,不行那到底是怎么实现的????因为这样子,所以工作上VC编程三年以来,我从不制造返回指针的函数,最多就是在参数中返回
      

  4.   

    思考了一下楼主提出的问题应该是属于内存的管理,分配了内存当然就需要释放否则就会资源泄露,然而也必须理解的是内存分配以后给出的指针是可以管理内存用的,当一个指针赋值给了另一个指针或者转化了控制的格式,并不一定代表后者的指针就取得了所有的控制的权利,前面的指针还是可以用来释放内存的,而这时再使用后者的指针就会发生野指针的情况
    本例中内存由time_t long_time;实现,而其内存空间也同样自己释放,所以不需要再次释放
    我想你提到的函数只是改变了指针对内存访问的方式,而不是重新再次分出新的内存使用
    知识浅薄如有不当之处请大家指正。
      

  5.   

    我还是不明白,我也实际跟踪过这个程序,newtime指向的地址跟long_time并没有任何联系
    程序也没有内存泄漏
    但是我在最后添加一个delete newtime程序也没有什么异常,这到底是为什么??????
    看来,我要为这个问题加分了
      

  6.   

    gmtime, mktime, and localtime all use a single statically allocated tm structure for the conversion. Each call to one of these routines destroys the result of the previous call.看MSDN的时候仔细点看,就在代码示例的上面
      

  7.   

    不过真别说,我的MSDN里面就是没有,呐:你的MSDN是啥版本来着?
    localtime
    Converts a time value and corrects for the local time zone.struct tm *localtime( const time_t *timer );Routine Required Header Compatibility 
    localtime <time.h> ANSI, Win 95, Win NT 
    For additional compatibility information, see Compatibility in the Introduction.LibrariesLIBC.LIB Single thread static library, retail version 
    LIBCMT.LIB Multithread static library, retail version 
    MSVCRT.LIB Import library for MSVCRT.DLL, retail version 
    Return Valuelocaltime returns a pointer to the structure result. If the value in timer represents a date before midnight, January 1, 1970, localtime returns NULL. The fields of the structure type tm store the following values, each of which is an int:tm_secSeconds after minute (0 – 59)tm_minMinutes after hour (0 – 59)tm_hourHours after midnight (0 – 23)tm_mdayDay of month (1 – 31)tm_monMonth (0 – 11; January = 0)tm_yearYear (current year minus 1900)tm_wdayDay of week (0 – 6; Sunday = 0)tm_ydayDay of year (0 – 365; January 1 = 0)tm_isdstPositive value if daylight saving time is in effect; 0 if daylight saving time is not in effect; negative value if status of daylight saving time is unknown. The C run-time library assumes the United States’s rules for implementing the calculation of Daylight Saving Time (DST). ParametertimerPointer to stored timeResThe localtime function converts a time stored as a time_t value and stores the result in a structure of type tm. The long value timer represents the seconds elapsed since midnight (00:00:00), January 1, 1970, coordinated universal time (UTC). This value is usually obtained from the time function.gmtime, mktime, and localtime all use a single statically allocated tm structure for the conversion. Each call to one of these routines destroys the result of the previous call.localtime corrects for the local time zone if the user first sets the global environment variable TZ. When TZ is set, three other environment variables (_timezone, _daylight, and _tzname) are automatically set as well. See _tzset for a description of these variables. TZ is a Microsoft extension and not part of the ANSI standard definition of localtime.Note   The target environment should try to determine whether daylight saving time is in effect.Example/* LOCALTIM.C: This program uses time to get the current time 
     * and then uses localtime to convert this time to a structure 
     * representing the local time. The program converts the result 
     * from a 24-hour clock to a 12-hour clock and determines the 
     * proper extension (AM or PM).
     */#include <stdio.h>
    #include <string.h>
    #include <time.h>void main( void )
    {
            struct tm *newtime;
            char am_pm[] = "AM";
            time_t long_time;        time( &long_time );                /* Get time as long integer. */
            newtime = localtime( &long_time ); /* Convert to local time. */        if( newtime->tm_hour > 12 )        /* Set up extension. */
                    strcpy( am_pm, "PM" );
            if( newtime->tm_hour > 12 )        /* Convert from 24-hour */
                    newtime->tm_hour -= 12;    /*   to 12-hour clock.  */
            if( newtime->tm_hour == 0 )        /*Set hour to 12 if midnight. */
                    newtime->tm_hour = 12;        printf( "%.19s %s\n", asctime( newtime ), am_pm );
    }
    OutputTue Mar 23 11:28:17 AM
    Time Management RoutinesSee Also   asctime, ctime, _ftime, gmtime, time, _tzset