Search code examples
c++debuggingctimelocaltime

Calendar function crashes when invoking 'localtime_s'


I'm trying to make a callendar, so I use time_t and localtime_s to store the time and date info and then store it in individual members of the Calendar class:

void Callendar::Initialize()
{
    time_t now = time(0);
    tm *localTime = null;
    localtime_s(localTime, &now);

    LocalSeconds = localTime->tm_sec;
    LocalMinutes = localTime->tm_min;
    LocalHours = localTime->tm_hour;
    LocalDays = localTime->tm_mday;
    LocalMonths = localTime->tm_mon;
    LocalYears = localTime->tm_year;
    DaysSinceSunday = localTime->tm_wday;
    DaysSinceJanuaryFirst = localTime->tm_yday;
    HoursDaylightSavings = localTime->tm_isdst;
}

All compiles fine, however at runtime I get:

Debug Assertion Failed!

Program: C:\Users\MyPC\Desktop\Framework\Framework\Debug\Framework.exe File: f:\dd\vctools\crt_bld\self_x86\crt\src\loctim64.c Line: 69

Expression: ( ptm != NULL )

After I close the failed assert message, I get a standart debug error at this line:

static __inline errno_t __CRTDECL localtime_s(struct tm * _Tm, const time_t * _Time)
{
    return _localtime64_s(_Tm, _Time);
}

Which is basically the result of calling *localtime_s(localTime, &now);* in Calendar:Initialize() Could I possibly using a deprecated version of this functionality?I know there are other functions to get localtime, but I don't know which is the "proper" one.Others have suggested to me that I shouldn't use 'localtime', but seemingly localtime_s isn't working out either.


Solution

  • Please see documentation

    Parameters

    _tm

    Pointer to the time structure to be filled in.

    Meaning that the function expects the first parameter to be a non null pointer to a valid tm instance.

    change

    tm *localTime = null;
    localtime_s(localTime, &now);
    

    to

    tm localTime;
    localtime_s(&localTime, &now);