I'm working with ManagementObjects and foreach loops in C#. Coverity is claiming that there is a leak in code like this:
ObjectQuery myQuery = new ObjectQuery("Select * from Win32_Printer");
using (ManagementObjectSearcher mySearcher = new ManagementObjectSearcher(myQuery))
{
// alloc_fn: A new resource is returned from allocation method Current.get
// var_assign: Assigning: mo = resource returned from mo$iterator.Current
foreach (ManagementObject mo in mySearcher.Get())
{
foreach (PropertyData p in mo.Properties)
{
// do stuff, maybe return a string
}
}
}
// leaked_resource: Returning without closing mo leaks the resource that it refers to
return "";
Is this a real leak or a false positive?
Is the using block even needed here (it was my initial attempt at avoiding a leak)?
My thinking is that this is a managed collection that implements IDisposable and the caller shouldn't be responsible for destroying it. I've seen the following code suggested before, but it seems like it's heading down the wrong path with more using blocks:
...
foreach (ManagementObject mo in mySearcher.Get()) using(mo)
...
ManagementObject
is disposable and it is not being disposed in that code. That's what the warning is about. It's a true positive.
The collection class (mySearcher.Get()
) also is not being disposed but it should be. Coverity should warn about it.
I have done very little WMI so far but it seems almost everything needs to be disposed. A nasty API. Win32 shines through.
If this is a throw away program I'd simply not worry about any of it. Otherwise, you probably need to dispose.