1 // RUN: %clang_tsan -O1 %s -o %t && %t 2>&1 | FileCheck %s 2 #include <pthread.h> 3 #include <stdlib.h> 4 #include <stdio.h> 5 #include <stddef.h> 6 #include <unistd.h> 7 8 int *mem; 9 pthread_mutex_t mtx; 10 11 void *Thread1(void *x) { 12 pthread_mutex_lock(&mtx); 13 free(mem); 14 pthread_mutex_unlock(&mtx); 15 return NULL; 16 } 17 18 void *Thread2(void *x) { 19 sleep(1); 20 pthread_mutex_lock(&mtx); 21 mem[0] = 42; 22 pthread_mutex_unlock(&mtx); 23 return NULL; 24 } 25 26 int main() { 27 mem = (int*)malloc(100); 28 pthread_mutex_init(&mtx, 0); 29 pthread_t t; 30 pthread_create(&t, NULL, Thread1, NULL); 31 Thread2(0); 32 pthread_join(t, NULL); 33 pthread_mutex_destroy(&mtx); 34 return 0; 35 } 36 37 // CHECK: WARNING: ThreadSanitizer: heap-use-after-free 38 // CHECK: Write of size 4 at {{.*}} by main thread{{.*}}: 39 // CHECK: #0 Thread2 40 // CHECK: #1 main 41 // CHECK: Previous write of size 8 at {{.*}} by thread T1{{.*}}: 42 // CHECK: #0 free 43 // CHECK: #{{(1|2)}} Thread1 44 // CHECK: SUMMARY: ThreadSanitizer: heap-use-after-free{{.*}}Thread2 45