@@ -126,8 +126,12 @@ void* _mi_os_get_aligned_hint(size_t try_alignment, size_t size)
126126 if (hint == 0 || hint > MI_HINT_MAX ) { // wrap or initialize
127127 uintptr_t init = MI_HINT_BASE ;
128128 #if (MI_SECURE > 0 || MI_DEBUG == 0 ) // security: randomize start of aligned allocations unless in debug mode
129- uintptr_t r = _mi_heap_random_next (mi_prim_get_default_heap ());
130- init = init + ((MI_SEGMENT_SIZE * ((r >>17 ) & 0xFFFFF )) % MI_HINT_AREA ); // (randomly 20 bits)*4MiB == 0 to 4TiB
129+ mi_heap_t * heap = mi_prim_get_default_heap ();
130+ // gh-123022: default heap may not be initialized in CPython in background threads
131+ if (mi_heap_is_initialized (heap )) {
132+ uintptr_t r = _mi_heap_random_next (heap );
133+ init = init + ((MI_SEGMENT_SIZE * ((r >>17 ) & 0xFFFFF )) % MI_HINT_AREA ); // (randomly 20 bits)*4MiB == 0 to 4TiB
134+ }
131135 #endif
132136 uintptr_t expected = hint + size ;
133137 mi_atomic_cas_strong_acq_rel (& aligned_base , & expected , init );
@@ -636,8 +640,12 @@ static uint8_t* mi_os_claim_huge_pages(size_t pages, size_t* total_size) {
636640 // Initialize the start address after the 32TiB area
637641 start = ((uintptr_t )32 << 40 ); // 32TiB virtual start address
638642 #if (MI_SECURE > 0 || MI_DEBUG == 0 ) // security: randomize start of huge pages unless in debug mode
639- uintptr_t r = _mi_heap_random_next (mi_prim_get_default_heap ());
640- start = start + ((uintptr_t )MI_HUGE_OS_PAGE_SIZE * ((r >>17 ) & 0x0FFF )); // (randomly 12bits)*1GiB == between 0 to 4TiB
643+ mi_heap_t * heap = mi_prim_get_default_heap ();
644+ // gh-123022: default heap may not be initialized in CPython in background threads
645+ if (mi_heap_is_initialized (heap )) {
646+ uintptr_t r = _mi_heap_random_next (heap );
647+ start = start + ((uintptr_t )MI_HUGE_OS_PAGE_SIZE * ((r >>17 ) & 0x0FFF )); // (randomly 12bits)*1GiB == between 0 to 4TiB
648+ }
641649 #endif
642650 }
643651 end = start + size ;
0 commit comments