@@ -538,11 +538,13 @@ tracemalloc_alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize)
538538 return NULL ;
539539
540540 TABLES_LOCK ();
541- if (ADD_TRACE (ptr , nelem * elsize ) < 0 ) {
542- /* Failed to allocate a trace for the new memory block */
543- TABLES_UNLOCK ();
544- alloc -> free (alloc -> ctx , ptr );
545- return NULL ;
541+ if (tracemalloc_config .tracing ) {
542+ if (ADD_TRACE (ptr , nelem * elsize ) < 0 ) {
543+ /* Failed to allocate a trace for the new memory block */
544+ TABLES_UNLOCK ();
545+ alloc -> free (alloc -> ctx , ptr );
546+ return NULL ;
547+ }
546548 }
547549 TABLES_UNLOCK ();
548550 return ptr ;
@@ -963,8 +965,11 @@ _PyTraceMalloc_Stop(void)
963965 if (!tracemalloc_config .tracing )
964966 return ;
965967
966- /* stop tracing Python memory allocations */
968+ /* stop tracing Python memory allocations,
969+ but not while something might be in the middle of an operation */
970+ TABLES_LOCK ();
967971 tracemalloc_config .tracing = 0 ;
972+ TABLES_UNLOCK ();
968973
969974 /* unregister the hook on memory allocators */
970975#ifdef TRACE_RAW_MALLOC
@@ -1317,6 +1322,12 @@ PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr,
13171322
13181323 gil_state = PyGILState_Ensure ();
13191324
1325+ if (!tracemalloc_config .tracing ) {
1326+ /* tracing may have been turned off as we were acquiring the GIL */
1327+ PyGILState_Release (gil_state );
1328+ return -2 ;
1329+ }
1330+
13201331 TABLES_LOCK ();
13211332 res = tracemalloc_add_trace (domain , ptr , size );
13221333 TABLES_UNLOCK ();
0 commit comments