8.05 new[] / delete[] Pairing Rules vs Zero-Heap Fixed-Capacity Bounded Vectors
💻 1. Annotated Source Code
#include <iostream> using namespace std; int main() { const int ARR_SIZE = 5; int arrSize = 0; cout << "Please enter an array size: "; cin >> arrSize; int* myArray = new int[arrSize]; for (int i = 0; i < arrSize; i++) { myArray[i] = i * 2; } for (int i = 0; i < arrSize; i++) { cout << myArray[i] << endl; } delete[] myArray; myArray = nullptr; return 0; }
📐 2. Architecture & UML Class Model
📚 3. Core C++ Concepts Deep-Dive
1. Array Allocation (new[]) vs Scalar Allocation (new)
Allocating an array of $N$ objects requires new Type[N]. The runtime allocates memory for all elements plus internal array-size metadata (often stored in an invisible header prefix).
2. The Mismatched Deallocation Trap
Deallocating an array with scalar delete ptr; instead of delete[] ptr; is Undefined Behavior. In non-trivial classes, scalar delete calls the destructor of only the first element (ptr[0]) and corrupts the heap metadata manager.
⚡ 4. Embedded Systems & Hardware Reality
1. The Embedded Solution: Bounded Capacity Containers
Embedded applications need array-like containers with dynamic size (count of active elements) but bounded maximum capacity (zero heap allocation). Libraries like Embedded Template Library (ETL) provide etl::vector<T, Capacity>:
- Storage is allocated directly inside the object (on the stack or in static RAM).
- Element count can vary from $0$ to $Capacity$.
- Zero dynamic memory allocations; zero heap fragmentation.
2. C++26 std::inplace_vector<T, N>
Standard C++26 standardizes this exact container as std::inplace_vector, bringing zero-heap vector semantics to modern C++ standard libraries.
💡 5. Production-Ready Embedded Refactoring
Here is an embedded fixed-capacity bounded array container with zero dynamic allocation:
#include <cstdint> #include <cstddef> #include <array> template <typename T, size_t Capacity> class BoundedVector { private: std::array<T, Capacity> data_{}; size_t size_{0}; public: constexpr bool push_back(const T& item) noexcept { if (size_ >= Capacity) return false; // Fixed capacity reached data_[size_++] = item; return true; } constexpr void clear() noexcept { size_ = 0; } constexpr size_t size() const noexcept { return size_; } constexpr size_t capacity() const noexcept { return Capacity; } constexpr T& operator[](size_t idx) noexcept { return data_[idx]; } constexpr const T& operator[](size_t idx) const noexcept { return data_[idx]; } };
📝 Knowledge Verification Quiz
Test your understanding of the C++ concepts and embedded microcontroller trade-offs covered in this guide. Click any option for instant feedback.
delete on an array allocated with new[] is undefined behavior. The runtime cannot determine the array length, destructors for subsequent elements are skipped, and heap bookkeeping is corrupted.