11.18 std::stack Mechanics, Stack Overflow Hazards, and MPU Guards
Executive Summary: Understanding LIFO stack adapters. We compare data structure stacks with the hardware MCU execution stack, explore stack overflow risks, and examine memory protection unit (MPU) stack watermarking.
💻 1. Annotated Source Code
#include <iostream> #include <stack> #include <string> using namespace std; void storeReverse(const string& origString, stack<char>& reverseStack); bool isPalindrome(const string& origString); void printResult(const string& origString); int main() { string strArray[5] = { "racecar", "fudge", "civic", "bob", "dogs" }; for (const string& str : strArray) { printResult(str); cout << endl; } return 0; } void storeReverse(const string& origString, stack<char>& reverseStack) { for (char c : origString) { reverseStack.push(c); } } bool isPalindrome(const string& origString) { stack<char> reverseStack; storeReverse(origString, reverseStack); for (char c : origString) { if (reverseStack.top() != c) { return false; } reverseStack.pop(); } return true; } void printResult(const string& origString) { cout << "Is \"" << origString << "\" a palindrome? " << boolalpha << isPalindrome(origString) << endl; }
📐 2. Architecture & UML Class Model
<<template class>>
std::stack<T, Container>
LIFO Adapter
Attributes / Data Members
#c : Container (defaults to std::deque<T>)
Operations / Methods
+push(val: const T&) : void[calls c.push_back]
+pop() : void[calls c.pop_back]
+top() : T&[calls c.back]
+empty() : bool const
+size() : size_t const
📚 3. Core C++ Concepts Deep-Dive
LIFO Stack Operations
std::stack provides push(), pop(), top(), and empty() using LIFO semantics.
⚡ 4. Embedded Systems & Hardware Reality
Hardware Call Stack Constraints
On microcontrollers, stack memory is shared between local variables and interrupt context saving. Stack overflow corrupts global variables silently unless MPU guards are enabled.
💡 5. Production-Ready Embedded Refactoring
💡 Production-Ready Refactor
template <typename T, size_t MaxDepth> class StaticStack { public: bool push(T val) { if (top_ >= MaxDepth) return false; data_[top_++] = val; return true; } T pop() { return data_[--top_]; } private: std::array<T, MaxDepth> data_; size_t top_ = 0; };
📝 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.
Q1. What is a primary danger of deeply nested recursive functions on microcontrollers?
Detailed Explanation:
Microcontrollers have limited stack memory (often 1KB-8KB); recursion risks overflowing into heap/static RAM.