Search code examples
c++g++warnings

Can I tell a function explicitly to not accept pointers to non-heap variables?


I've noticed that g++ is smart enough to identify when a function is returning a pointer to a temporary/local variable, e.g.

int *foobar()
{
      int a;
      return &a;
}

Will result in:

 warning: address of local variable ‘a’ returned

Is there a way that I can define a function prototype to only accept pointers that the compiler can tell are not temporary. So lets say I have a function

 barfoo(int *a_int);

Is there a way I can tell g++ to complain if someone passes a pointer to a local/temporary object into it? This would prohibit people from calling barfoo with invalid pointers and potentially save debugging some annoying issues.

Example:

   void barfoo(int *a)
   {
        cerr << a << endl;
   };

   void foobar()
   {
        int a;
        barfoo(&a);
   }

I would like the compiler to complain about the `barfoo(&a)'.


Solution

  • I don't think there is any way to get the compiler to enforce it, but you can detect some instances earlier by using malloc_size.

    void someFunc(int * mustBeHeap) {
       assert(0!=malloc_size(mustBeHeap));
       //do stuff
    }
    

    Unfortunately you will get false positives from code like this:

    void someOtherFunc() {
        int * myInts=(int *)malloc(sizeof(int)*20);
        someFunc(&(myInts[3]));
    }
    

    It won't work too well with anything allocated with new, boost::pool, etc. In fact, you will get false positives from just about everything.

    Also, malloc_size is non-standard.

    Edit:

    After looking at one of your comments above about taking ownership, it looks like some of the things I described as false positives are in fact situations you also want to detect since you intended to free the memory from the pointer.