localtime() - segmentation fault

两盒软妹~` 提交于 2019-12-13 01:52:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!