Page 1 of 1

Where is this memory leaking when using static strings within functions while using threads?

Posted: Wed Oct 13, 2021 12:02 pm
by Mistrel
Tested with the latest PureBasic 5.73. I was experimenting with threads when I spotted this.

The PureBasic application will continue to consume memory until it crashes:

Code: Select all

Procedure.s FuncStaticString()
  Static string.s
  
  string.s=LSet("",32,Chr(97+Random(25,0)))
EndProcedure

Procedure ThreadTest(null)
  FuncStaticString()
EndProcedure

NewList threadPool()
threadCount.q=0

For i=1 To 10000
  AddElement(threadPool())
  thread=CreateThread(@ThreadTest(),#Null)
  
  If Not thread
    Debug "Last thread count: "+Str(threadCount)
    
    DebuggerError("Thread entry is null")
  EndIf
  
  threadPool()=thread
  threadCount+1
  
  If i=10000
    i=1
    
    ForEach threadPool()
      If Not threadPool()
        DebuggerError("Thread entry is null")
      EndIf
      
      WaitThread(threadPool())
    Next
    
    ClearList(threadPool())
  EndIf
Next i
This is interesting because the pointer to a static string within a procedure doesn't change. So where is the memory leaking from? Maybe the temporary string created during assignment isn't being freed?

Re: Where is this memory leaking when using static strings within functions while using threads?

Posted: Wed Oct 13, 2021 12:22 pm
by #NULL
I'm not sure I can reproduce on linux, maybe mem is growing. But aren't you accessing a single static variable from multiple threads without protection by mutex etc.? If multiple threads want to reallocate the string mem behind string and reassign the pointer, some mem might get lost, or the pointer corrupted in a non-atomic write. I'm not sure though. :)

Re: Where is this memory leaking when using static strings within functions while using threads?

Posted: Wed Oct 13, 2021 12:57 pm
by infratec
You need definately a mutex.