--- title: Warning C26407 description: "Reference for Visual Studio C++ Core Guidelines code analysis warning C26407." ms.date: 08/18/2020 f1_keywords: ["C26407", "DONT_HEAP_ALLOCATE_UNNECESSARILY"] helpviewer_keywords: ["C26407"] ms.assetid: 5539907a-bfa0-40db-82a6-b860c97209e1 --- # Warning C26407 > Prefer scoped objects, don't heap-allocate unnecessarily (r.5) To avoid unnecessary use of pointers, we try to detect common patterns of local allocations. For example, we detect when the result of a call to operator **`new`** is stored in a local variable and later explicitly deleted. This check supports the [C++ Core Guidelines rule R.5](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r5-prefer-scoped-objects-dont-heap-allocate-unnecessarily): *Prefer scoped objects, don't heap-allocate unnecessarily*. To fix the issue, use an RAII type instead of a raw pointer, and allow it to deal with resources. Obviously, it isn't necessary to create a wrapper type to allocate a single object. Instead, a local variable of the object's type would work better. ## Remarks - To reduce the number of warnings, code analysis only detects this pattern for owner pointers. So, it's necessary to mark owners properly first. We can easily extend this analysis to cover raw pointers if we receive feedback on the Visual Studio C++ [Developer Community](https://aka.ms/feedback/suggest?space=62) from customers in support of such scenarios. - The *scoped object* term may be a bit misleading. In general, we suggest you use either a local variable whose lifetime is automatically managed, or a smart object that efficiently manages dynamic resources. Smart objects can do heap allocations, but it's not explicit in the code. - If the warning fires on array allocation, which is often needed for dynamic buffers, you can fix it by using standard containers, or `std::unique_pointer`. - The pattern is detected only for local variables. We don't warn in cases where an allocation is assigned to, say, a global variable and then deleted in the same function. Code analysis name: `DONT_HEAP_ALLOCATE_UNNECESSARILY` ## Example 1: Unnecessary object allocation on heap ```cpp auto tracer = new Tracer(); ScanObjects(tracer); delete tracer; // C26407 ``` ## Example 2: Unnecessary object allocation on heap (fixed with local object) ```cpp Tracer tracer; // OK ScanObjects(&tracer); ``` ## Example 3: Unnecessary buffer allocation on heap ```cpp 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) ```cpp auto value = std::vector(maxValueSize); // OK if (ReadSetting(name, value.data(), maxValueSize)) CheckValue(value.data()); ```