https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105204

            Bug ID: 105204
           Summary: -Wuse-after-free=1 inconsistency with conditional free
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: piotr.grabowski at scylladb dot com
  Target Milestone: ---

Created attachment 52772
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=52772&action=edit
two examples of conditional free

Below, I added two examples of conditional free(), which cause inconsistent
behavior of -Wuse-after-free=1. 

In the first case, GCC 12 does not issue -Wuse-after-free=1 warning, but in the
second similar example, the warning is triggered.


// Compile with: g++ -Wuse-after-free=1 -O2 -c example-inconsistency.cpp
void example1(int* ptr, bool condition) {
    if (condition) {
        free(ptr);
    }
    ++*ptr; // No -Wuse-after-free=1 warning
}

void example2(int* ptr) {
    if (*ptr == 1234) {
        free(ptr);
    }
    ++*ptr; // -Wuse-after-free=1 warning issued
}


Compiled with: g++ (GCC) 12.0.1 20220404 (experimental)

We hit that second case in our production code in our implementation of shared
pointer in Seastar
(https://github.com/scylladb/seastar/blob/05cdfc2d30c553ec73b5cdbfb6c4318c232b3a6d/include/seastar/core/shared_ptr.hh#L255).
Below is a simplified version of it, which triggers -Wuse-after-free=1:


// Compile with: g++ -Wuse-after-free=1 -O2 -c example-shared-ptr.cpp
struct shared_ptr {
    size_t* ref_count;
public:
    shared_ptr(const shared_ptr& other) : ref_count(other.ref_count) {
        (*ref_count)++;
    }
    ~shared_ptr() {
        if (--(*ref_count) == 0) {
            free(ref_count);
        }
    }
};

void example3(shared_ptr& sp) {
    shared_ptr sp2(sp);
    shared_ptr sp3(sp);
    // -Wuse-after-free=1 is issued
}


Is this the expected behavior of -Wuse-after-free=1 and we should work around
it in our code?

Reply via email to