Search code examples
c++timecrashexc-bad-accesslocaltime

Crash in localtime() but gmtime() works


I have an EXC_BAD_ACCESS in the function below:

time_t dateTime(getCurrentTimestamp());
tm *calculatedTime;
calculatedTime = localtime(&dateTime); 
tm *dateTimeCopy = new tm();
memcpy(dateTimeCopy, calculatedTime, sizeof(tm));
return dateTimeCopy;

The EXC_BAD_ACCESS happens in localtime(). Which I can not explain. If I change local time to gmtime it is working just fine. What could be the reason for this behaviour?

EDIT: Fixed an error in this code. As mentioned by Rufflewind. The crash still exists however.

EDIT 2: With localtime_r it is working as well. I will probably end up using it as shown below:

time_t dateTime(valueDateTime);
tm *dateTimeCopy = new tm();
localtime_r(&dateTime, dateTimeCopy);

Solution

  • As stated in a comment above we moved completely away from using the localtime function. It accesses shared memory and seems to be not thread save or having other issues (at least in clang / ios / mac os).

    We moved to use localtime_r or similar functions which seem to work without issues. Here is the code again which I also posted in the Question itself:

    time_t dateTime(valueDateTime);
    tm *dateTimeCopy = new tm();
    localtime_r(&dateTime, dateTimeCopy);