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

Just starting out? Need help? Post your questions and find answers here.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

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

Post 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?
#NULL
Addict
Addict
Posts: 1440
Joined: Thu Aug 30, 2007 11:54 pm
Location: right here

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

Post 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. :)
infratec
Always Here
Always Here
Posts: 6817
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

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

Post by infratec »

You need definately a mutex.
Post Reply