Skip to content

Latest commit

 

History

History
53 lines (39 loc) · 2.31 KB

File metadata and controls

53 lines (39 loc) · 2.31 KB
title C26407
ms.date 07/21/2017
ms.topic conceptual
f1_keywords
C26407
helpviewer_keywords
C26407
ms.assetid 5539907a-bfa0-40db-82a6-b860c97209e1

C26407 DONT_HEAP_ALLOCATE_UNNECESSARILY

To avoid unnecessary use of pointers we try to detect common patterns of local allocations, for example when the result of a call to operator new is stored in a local variable and later explicitly deleted. This supports the rule R.5: Prefer scoped objects, don't heap-allocate unnecessarily. The suggested fix is to use an RAII type instead of a raw pointer and allow it to deal with resources. If an allocation is a single object, then it may be obviously unnecessary and a local variable of the object’s type would work better.

Remarks

  • To reduce the number of warnings, this pattern is detected for owner pointers only. So, it is necessary to mark owners properly first. We can easily extend this to cover raw pointers if we receive feedback from customers in support of such scenario.

  • The scoped object term may be a bit misleading, but the general idea is that we suggest using either a local variable whose lifetime is automatically managed, or a smart object which efficiently manages dynamic resources. Smart objects can of course do heap allocations, but it is not explicit in the code.

  • If the warning fires on array allocation (which is usually needed for dynamic buffers), the fix can be to use standard containers, or std::unique_pointer<T[]>.

  • The pattern is detected only for local variables, so we don’t warn on cases where an allocation is assigned to, say, a global variable and then deleted in the same function.

Example 1: Unnecessary object allocation on heap

auto tracer = new Tracer();
ScanObjects(tracer);
delete tracer;  // C26407

Example 2: Unnecessary object allocation on heap (fixed with local object)

Tracer tracer;  // OK
ScanObjects(&tracer);

Example 3: Unnecessary buffer allocation on heap

auto value = new char[maxValueSize];
if (ReadSetting(name, value, maxValueSize))
    CheckValue(value);
delete[] value; // C26407

Example 4: Unnecessary buffer allocation on the heap (fixed with container)

auto value = std::vector<char>(maxValueSize); // OK
if (ReadSetting(name, value.data(), maxValueSize))
    CheckValue(value.data());