Main Content

Missing call to container's reserve method

A fixed number of items are added to a container without calling the reserve() method of the container beforehand, resulting in inefficient code

Since R2022b

Description

This defect occurs when you add a fixed number of items to a container without preallocating the necessary memory by calling the reserve() method of the container.

This code inserts three items into the vector v but does not preallocate the required memory by calling v.reserve().

//...
std::vector< int > v;
    v.push_back( 0 ); 
    v.push_back( 1 );
    v.push_back( 2 ); 
Polyspace® reports a defect.

Risk

If you do not preallocate sufficient memory by calling the reserve() method of a container, insertion operations might allocate progressively larger chunks of memory, resulting in inefficient code. Allocating sufficient memory before the insertion operations allows for efficient use of memory and might allow for faster execution.

Fix

Call the reserve() method of the container to preallocate memory. If you are able to use C++11, use std::initializer_lists to insert a known number of elements.

Performance improvements might vary based on the compiler, library implementation, and environment that you are using.

Examples

expand all

#include <vector>

void fill_3() {
    std::vector< int > v;
    v.push_back( 0 ); /* Defect */
    v.push_back( 1 );
    v.push_back( 2 );
}

In this example, the function fill_3 pushes three elements into a vector. Because the number of elements to be inserted is known, reserving memory for them beforehand might make the code more efficient. Polyspace reports a defect on the inefficient code.

Correction — Preallocate Necessary Memory

Call the reserve() method of the container to preallocate the necessary memory before the insertion operations.

#include <vector>

void fill_3() {
    std::vector< int > v;
    v.reserve( 3 );
    v.push_back( 0 ); /* Defect */
    v.push_back( 1 );
    v.push_back( 2 );
} 
Correction — Use std::Initializer_list

If the number of elements to be inserted and their values are known, use an initializer_list to initiate the container. This solution applies to C++11 and later.

#include <vector>

void fill_3() {
    std::vector< int > v{0,1,2};
} 

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: MISSING_CONTAINER_RESERVE
Impact: Medium

Version History

Introduced in R2022b