Localtime () - segmentation error

I have this code that returns the day of the week from the date, for example, "29-02-2016", but sometimes it gives me a segmentation error in localtime (& t).

int obterDiaSemana(char *str) {
 struct tm tm2;
 if(strptime(str, "%d-%m-%Y", &tm2) != NULL) {
  time_t t = mktime(&tm2);
  return localtime(&t)->tm_wday; //Sunday=0, Monday=1, etc.
 }
 return -1;
}

function gets:

 char userDate[10]="29-02-2016";

I was looking for a solution, but I can not solve it.

Thanks in advance.

If you need more information, just let me know.

0
source share
2 answers

You do not initialize struct tm tm2. When it is passed to strptime, only the members specified in the format string "%d-%m-%Y"are set with values, others remain unchanged, in this case uninitialized, so their values ​​are undefined.

tm2 mktime() undefined.

, .


userDate , "29-02-2016".

+2

: tm2, . mktime , (time_t) -1. localtime((time_t)-1) segfault.

tm2 , localtime -1.

+1

All Articles