[cfe-dev] Ownership attribute for malloc etc. checking

Ted Kremenek kremenek at apple.com
Thu Jul 1 22:18:32 PDT 2010


On Jul 1, 2010, at 8:08 PM, Andrew McGregor wrote:

> Ok, I get what you're saying, PreVisit seems the right answer.
> 
> On Fri, Jul 2, 2010 at 2:41 PM, Jordy Rose <jediknil at belkadan.com> wrote:
> 
> 
> > struct it *  __attribute((ownership_returns(malloc))) foo(void) {
> >   struct it *rv = malloc(sizeof(struct it));
> >   if (!rv)
> >     return NULL; // Does not warn here.
> >   char *textString = malloc(128*sizeof(char));
> >   if(textString == NULL)
> >     free(rv);
> >     return NULL; // Warns about a memory leak here
> >   rv->s = textString;
> >   return rv; // Does NOT warn here
> > }
> 
> ...the code is just missing braces around the second if -- the second
> "return NULL" is unconditional!
> 
> Clang should catch this. Filing a bug. *grin*
> 
> D'oh!
> 
> So looking at this version:
> 
> void  __attribute((ownership_returns(malloc))) foo2(void) {
>   struct it *rv = malloc(sizeof(struct it));
>   if (!rv)
>     return NULL;
>   char *textString = malloc(128*sizeof(char));
>   if(textString == NULL) {
>     free(rv);
>     return NULL;
>   }
>   rv->s = textString;
>   return rv; // warns of a leak here
> }
> 
> How could I make the assignment before the final return relinquish ownership of the pointer?

CheckerVisitor also supports PreVisitBind (which is callback that occurs before the RHS gets bound to the LHS).  You can use that to monitor ownership transfer.  We can also add PostVisitBind if that would be useful.

That said, what are the semantics of the ownership algorithm?  Does a leak get flagged here, or does the escape of the value to a field silence the warning?

FWIW, ownership checking in the presence of data containers has been researched quite a bit.  Here's some off-hand references that might be useful:

Static Detection of Leaks in Polymorphic Containers, ICSE 2006
http://suif.stanford.edu/~dlheine/icse06-preprint.pdf

A practical flow-sensitive and context-sensitive C and C++ memory leak detector
http://portal.acm.org/citation.cfm?doid=781131.781150

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20100701/5527cb90/attachment.html>


More information about the cfe-dev mailing list