Search code examples
c#asp.netcoveritycoverity-prevent

Coverity issue: noescape: Resource dataview is not closed or saved in Table.get


this.btnSaveChanges.Visible = false;        
//Error: alloc_fn: A new resource is returned from allocation method Grp_des.
//Error: var_assign: Assigning: dtv = resource returned from this.dal.Grp_des(this.sParent).
DataView dtv = dal.Grp_des("ABC"); 
**//error:  noescape: Resource dtv is not closed or saved in Table.get.**
DataRow dtr = dtv.Table.Rows[0];
lblTransferFrom.Text = "Job Transferred from:  " + HttpUtility.HtmlEncode(dtr[0].ToString());
//Error: leaked_resource: Variable dtv going out of scope leaks the resource it refers to.

What exactly both the error's pointing? Can any one help me in this, Thank you in advance.


Solution

  • I can explain what the messages mean, including noescape.

    this.btnSaveChanges.Visible = false;        
    //Error: alloc_fn: A new resource is returned from allocation method Grp_des.
    //Error: var_assign: Assigning: dtv = resource returned from this.dal.Grp_des(this.sParent).
    DataView dtv = dal.Grp_des("ABC"); 
    

    The alloc_fn event means Coverity thinks that Grp_des allocates a resource that must be disposed. Then var_assign says that resource is pointed to by the dtv variable.

    **//error:  noescape: Resource dtv is not closed or saved in Table.get.**
    DataRow dtr = dtv.Table.Rows[0];
    

    The noescape event is purely informative. Coverity is saying that, although dtv was passed to Table.get, that method does not dispose of the resource, and also does not save it in a field. Consequently, the resource is still allocated and still needs to be disposed.

    This particular event is notoriously confusing. The static analysis jargon term "escape" describes what happens when a value is saved to a field or a global. "noescape" means that didn't happen.

    lblTransferFrom.Text = "Job Transferred from:  " + HttpUtility.HtmlEncode(dtr[0].ToString());
    //Error: leaked_resource: Variable dtv going out of scope leaks the resource it refers to.
    

    Finally, the leaked_resource event indicates that we have reached the end of this method and the resource still has not been either disposed or saved for later disposal. This is usually bad because the resource will not be disposed until the garbage collector reclaims the associated memory object, which could be a long time from now, and something could starve for the resource in question in the meantime.

    The straightforward fix would be to add dtv.Dispose(); at the end or to use a using statement to do disposal automatically and in an exception-safe way. But, of course, without seeing the rest of the code, it's impossible to be sure that is the correct fix.

    (Disclosure: I used to work for Coverity/Synopsys.)