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

            Bug ID: 101781
           Summary: make_unique generating a warning with -fanalyzer
           Product: gcc
           Version: 11.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: deco33000 at yandex dot com
  Target Milestone: ---

Hi,

given the following code

// Type your code here, or load an example.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;

int main() {

    auto res = make_unique<int>();
    auto ptr = res.get();

    if (ptr) {

        *ptr = 5;
        cout << *ptr << endl;

    }

  return 0;
}
I get warning: dereference of possibly-NULL 'operator new(4)' [CWE-690]
[-Wanalyzer-possible-null-dereference]

Whereas I check sufficiently not to dereference that pointer if not set.
Apparently, the compiler doesn't like that make_unique doesn't check the return
of new. Even then, the code avoiding make_unique:

int main() {

    auto i = new int(0);

    if (!i) {

        return 1;
    }

  unique_ptr<int> res(i);
  auto ptr = res.get();

  if (!ptr) {
    return 1;
  }
  *ptr = 5;
  cout << *ptr << endl;

  return 0;
}      

Still gives the same warning.

try on Godbolt:
https://godbolt.org/z/8399T1511
and
https://godbolt.org/z/5jjM4E5Ec

Thanks

Reply via email to