Search code examples
cdatetimestrptime

strptime() causes EXC_BAD_ACCESS


I'm trying to parse a string into a tm struct using the strptime() function.

int main(int argc, const char * argv[]) {
    char raw_date1[100];
    char date1[100];
    struct tm *timedata1 = 0;

    printf("please provide the first date:");
    fgets(raw_date1, sizeof(raw_date1), stdin);

    strip_newline(date1, raw_date1, sizeof(raw_date1));

    char format1[50] = "%d-%m-%Y";

    strptime(date1, format1, timedata1);

On the last line, the program crashes with the message: EXC_BAD_ACCESS (code=1, address=0x20).

Why?

Some extra info: According to the debugger, at the time of the crash, date1 is 23/23/2323, format1 is "%d-%m-%Y" and timedata1 is NULL.


Solution

  • In your code:

    struct tm *timedata1 = 0;
    

    is the same as

    struct tm *timedata1 = NULL;
    

    Consequently, statement

    strptime(date1, format1, timedata1);
    

    is the same as

    strptime(date1, format1, NULL);
    

    i.e., in your code, you pass NULL as argument to strptime, which will dereference the pointer and yield undefined behaviour / bad access.

    So you should write something like the following:

    struct tm timedata1 = {0};
    strptime(date1, format1, &timedata1);