0

Look at this code:

int nIndicrs = 2*nSides;
auto* arr = new int[nIndices];
if(!arr) return false;

My clang-tidy tool complains that the if will always be true. Why?

Shouldn't I get a nullptr in case the allocation fails? What's the proper way to test a successful new call?

If it makes any difference, this code is using c++ 11 being compiled using Android ndk v21.3.

Zack
  • 119
  • 2
  • 13
  • 1
    fwiw, I'm partial to this [answer](https://stackoverflow.com/a/6834029/8372853) from the dupe. – cigien Oct 07 '20 at 23:32
  • 1
    Side note: Prefer [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) for this job. Among other bonus features, `std::vector arr(nIndices);` will manage the memory for you. – user4581301 Oct 07 '20 at 23:32
  • I can't spot any mention of `nullptr` [here](https://en.cppreference.com/w/cpp/language/new)? – πάντα ῥεῖ Oct 07 '20 at 23:34
  • @user4581301 But I have no intention of resizing that buffer. I can compute it's size in advamce. Furthermore, im filling it with data, sending it to the GPU and delete it, all in the same method. Is std::vector would be best for that use case? – Zack Oct 07 '20 at 23:38
  • 1
    The ability of a `vector` to resize itself is a bonus feature here. In your use case `vector`'s observance of [RAII](https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii) and the [Rules of Three and Five](https://en.cppreference.com/w/cpp/language/rule_of_three) are potentially more important. Many programs that simply want a temporary buffer and use `new` find themselves leaking when the function containing the buffer exits unexpectedly without passing though a `delete[]`. – user4581301 Oct 07 '20 at 23:41
  • Well, how about having int mybuff[method-param] without a new? After postint my question I have noticed I have tgat im my xode a few lines above the allocation. No comiler error. No new, delete or try-catch. What would be wrong with this kind of a temp buffer? – Zack Oct 08 '20 at 00:05
  • @user4581301 thanks for theeule of three and five pointer btw. That's new to me. – Zack Oct 08 '20 at 00:08
  • If you can use an automatically allocated buffer of sufficient size, definitely do. Almost always the faster approach. For example if you know the size cannot get bigger than X and X isn't so large that it'll exhaust automatic storage (AKA cause a stack overflow), allocate enough for X. Simple. stupid and only wasteful for the few moments you need the buffer. – user4581301 Oct 08 '20 at 00:20

0 Answers0