4.01 Fixed-Size C Arrays, Stack Allocation & Array Decay to Raw Pointers
💻 1. Annotated Source Code
#include <iostream> using namespace std; int main() { const int ARRAY_SIZE = 5; int myArray[ARRAY_SIZE]; myArray[0] = 15; myArray[1] = 20; myArray[2] = 22; myArray[3] = 13; myArray[4] = 6; for (int i = 0; i <= ARRAY_SIZE; i++) { cout << myArray[i] << endl; } return 0; }
📐 2. Architecture & UML Class Model
📚 3. Core C++ Concepts Deep-Dive
1. Contiguous Stack Allocation
A C-style array (int arr[5]) allocates a contiguous sequence of elements directly on the current stack frame. The variable name arr represents the starting memory address of the block.
2. The Array-to-Pointer Decay Trap
When passed to a function (void print(int arr[])), the array decays into a raw pointer (int*). sizeof(arr) inside the function returns the pointer size (4 or 8 bytes), NOT the total array size!
⚡ 4. Embedded Systems & Hardware Reality
1. Stack Buffer Overflows & Return Address Hijacking
In microcontrollers without virtual memory protection, writing beyond an array index corrupts the function's saved Link Register (LR) / Return Address on the stack frame. When the function returns, the CPU jumps to an arbitrary address, causing execution hijacking or HardFault crashes.
2. MISRA C++:2008 Rule 5-0-15
Array indexing shall be the only form of pointer arithmetic. Pointer decay when passing arrays across API boundaries is strongly discouraged in favor of std::array or bounded span wrappers.
💡 5. Production-Ready Embedded Refactoring
Replace raw decaying arrays with zero-overhead, size-preserving std::array:
#include <cstdint> #include <array> // Type-safe, non-decaying array parameter template <size_t N> void processSamples(const std::array<uint16_t, N>& samples) noexcept { static_assert(N > 0, "Sample buffer cannot be empty"); for (uint16_t val : samples) { // Process sensor sample... } }
📝 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.
int*), discarding container size information.
sizeof(arr) evaluates to the pointer size (4 bytes), yielding 4 / 4 = 1.
std::array contains only the underlying C array internally with zero extra members, making its size and memory layout identical to a raw array.