Valgrind error: invalid read / write in pthread_cancel in wait state

Valgrind reports an invalid read / write to pthread_cond_wait () if the thread is canceled while it is waiting in state. Not sure why this is happening, or if this is a known issue:

==321== Invalid write of size 4
==321==    at 0x4DF5785: _Unwind_ForcedUnwind (in /lib/i386-linux-
gnu/libgcc_s.so.1)
==321==    by 0x4059E1A: pthread_cond_timedwait@@GLIBC_2.3.2 
(pthread_cond_timedwait.S:245)
==321==    by 0x49DE28F: ???
==321==  Address 0x49de210 is on thread 2 stack
==321== 
==321== Invalid read of size 4
==321==    at 0x4DF579D: _Unwind_ForcedUnwind (in /lib/i386-linux-
gnu/libgcc_s.so.1)
==321==  Address 0x49de210 is on thread 2 stack

Minimal executable code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>

static pthread_cond_t notification_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t notification_mutex = PTHREAD_MUTEX_INITIALIZER;
time_t interval = 0;
pthread_t thread;
struct timespec ts;

void cleanup_handler(void *plock)
{
    pthread_mutex_unlock(plock);
}

void *wait_on_condition(void *arg)
{
    pthread_cleanup_push(cleanup_handler, &notification_mutex);
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    interval = time(NULL) + 5; //(If we replace 5 with 0, code just runs fine)
    ts.tv_nsec = 0;
    ts.tv_sec = interval;

    pthread_mutex_lock(&notification_mutex);
    pthread_cond_timedwait(&notification_cond, &notification_mutex, &ts);
    pthread_mutex_unlock(&notification_mutex);
    pthread_cleanup_pop(0);
}

int main(int argc, char **argv)
{
    pthread_create(&thread, NULL, wait_on_condition, NULL);
    pthread_cancel(thread);
    pthread_join(thread, NULL);

    return 0;
}
+4
source share

Source: https://habr.com/ru/post/1685685/


All Articles