问题
I have this code that return the week day from a date like "29-02-2016", but sometimes it gives me segmentation fault 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;
}
the function receives:
char userDate[10]="29-02-2016";
I've been looking for a solution but cant solve this.
Thanks in advance.
If you need some additional info just let me know.
回答1:
You are not initializing struct tm tm2
. When it is passed to strptime, only members specified in the format string "%d-%m-%Y"
are set with values, others are left unchanged, in this case uninitialized, so their values are indeterminate.
Passing that partially initialized struct tm2
to mktime() will result in undefined behavior.
You will need to initialize the struct with some values, preferably with zeroes.
And array userDate is too small to contain "29-02-2016"
.
回答2:
Two problems in this code: You don't initialize tm2, so it may hold any values. If mktime does not like its parameter it will return (time_t)-1. Calling localtime((time_t)-1)
seems to crash with a segfault.
You should initialize tm2
and check if localtime
returns -1.
来源:https://stackoverflow.com/questions/35536990/localtime-segmentation-fault