1

I have an issue with a simple function (I guess because of some wrong pointer assigment). As strptime function (a function that takes a string and gives back a struct tm with all the data set) is not present in Windows, I created a sort of strptime function by calling other base working functions.

Here's the test code. Inside the STRPTIME function, time is well set, while then in main I lose the info.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void STRPTIME(char *strtm, struct tm *tminfo)
{
    time_t rawtime;
    int day, month, year;

    sscanf(strtm, "%d-%d-%d\n", &year, &month, &day);
    time( &rawtime );
    tminfo = localtime( &rawtime );
    tminfo->tm_year = year - 1900;
    tminfo->tm_mon  = month - 1;
    tminfo->tm_mday = day;

    mktime(tminfo);
    printf("date %d-%d-%d\n", tminfo->tm_year, tminfo->tm_mon, tminfo->tm_mday);
}

int main()
{
    char stm[11];
    struct tm tminfo;

    strcpy(stm, "2015-12-31");
    STRPTIME(stm, &tminfo);

    printf("tminfo %d-%d-%d\n", tminfo.tm_year, tminfo.tm_mon, tminfo.tm_mday);

    return(0);
}
Stefano
  • 361
  • 1
  • 4
  • 21

1 Answers1

0

The problem is that you're overwriting the pointer of your tminfo argument.

tminfo = localtime( &rawtime );

A function argument is like a local variable: you can overwrite it. It lives on the stack. But your caller will not notice this change.

You need to do something like this:

// Store the result in a temporary variable.
struct tm * tmp = localtime( &rawtime );
if ( tmp && tminfo ) {
    // Copy to caller's memory.
    memcpy( tminfo, tmp, sizeof( *tmp ) );
}
DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • you're totally right!! I didn't think of it! the `if` is a check to be sure that localtime gives back not `NULL` and the input is `NULL` either, right? – Stefano May 06 '16 at 13:19
  • btw, is this solution a good one to overtake the strptime problem or there's something fancier and above all faster? – Stefano May 06 '16 at 13:20
  • 1
    Yes, the `if` makes sure that both the result of `localtime` and the function's argument are not `NULL`, as the two arguments to `memcpy` must not be `NULL`. Since your version of `strptime` doesn't have a `format` argument it's not really equivalent. So whether it's "good enough" probably depends on your use case. See also [this question](http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows). – DarkDust May 06 '16 at 13:29
  • yeah, I have just one `format` and in fact I was trying to do what one of those guys suggested. Thanks again! – Stefano May 06 '16 at 13:32