简体   繁体   中英

Strange behavior of gmtime_r

int main() {
    time_t *ptr;
    struct tm *dates;
    time(ptr);
    gmtime_r(ptr, dates);
    size_t a = 20; //<-- works with int
    return 0;
}

It fails with Segmentation fault (core dumped) error. When I use int instead of size_t everything works fine. When I change gmtime_r to non-thread-safety gmtime it works too though I have to add declaration of pointer which gmtime will assign to. Declaration of gmtime_r .

gcc version is 5.4.0, compile with gcc -Wall -oa test.c , 64-bit ubuntu.

Not strange at all; you need to allocate what dates points to, so gmtime_r can fill it. And what ptr points to, so time can fill that.

Pointers in C are just that, they identify a location where data might be (or might not, in which case undefined behavior is the rule).

int main() {
    time_t ptr; // Actual storage for time_t
    struct tm dates; // Actual storage for struct tm
    time(&ptr); // Pointer to a time_t
    gmtime_r(&ptr, &dates); // Pointer to a time_t, pointer to a
    // struct tm
    size_t a = 20; //<-- works with int
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM