LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   gcc 4.6.3 incorrectly detects free() of non-heap object (https://www.linuxquestions.org/questions/programming-9/gcc-4-6-3-incorrectly-detects-free-of-non-heap-object-4175431092/)

samjam 10-08-2012 05:46 AM

gcc 4.6.3 incorrectly detects free() of non-heap object
 
This gcc code:

Code:

void* d __attribute__((cleanup(free))) = malloc(size);

gives this error:

Code:

attempt to free a non-heap object ‘d’ [-Werror]
It seems like d is a heap object, so is the error with me or gcc 4.6.3?

This works however,

Code:

void *d  = malloc(size);
free(d);

Which makes me think this is a gcc error

I can't find a simple pragma to disable this check; this fails:
Code:

#pragma GCC diagnostic ignored "-Wno-free-nonheap-object"

JohnGraham 10-08-2012 06:09 AM

From the GCC documentation on the cleanup attribute:

Quote:

The function must take one parameter, a pointer to a type compatible with the variable.
Thus, you need to create your own function that takes a void**. With this short example, GCC does not complain (and valgrind says it's happy):

Code:

#include <stdlib.h>

void free_ptr(void **ptr)
{
    free(*ptr);
}

int main(void)
{
    void *d __attribute((cleanup(free_ptr))) = malloc(20);
}

Edit:

So your original problem was that &d was being passed to free(), which of course bad.

samjam 10-08-2012 06:25 AM

Quote:

Originally Posted by JohnGraham (Post 4800123)
From the GCC documentation on the cleanup attribute:

Thus, you need to create your own function that takes a void**. With this short example, GCC does not complain (and valgrind says it's happy):

Thank-you. I'm sure I knew that once. Much appreciated.


All times are GMT -5. The time now is 07:03 AM.