Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int freeRam ()
- {
- extern int __heap_start, *__brkval;
- int v;
- return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
- }
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(115200);
- recurse(1);
- }
- void loop() {
- // put your main code here, to run repeatedly:
- }
- void recurse(long i) {
- Serial.println(i);
- recurse(i+1);
- }
- /*
- stack_overflow
- - a quick program to force a stack overflow in order to see how many stack frames in a small function can be loaded onto the stack before the overflow occurs
- By Gabriel Staples
- www.ElectricRCAircraftGuy.com
- Written: 6 Nov 2017
- Updated: 6 Nov 2017
- References:
- - Jumping into C++, by Alex Allain, pg. 230 - sample code here in the chapter on recursion
- To compile and run:
- Compile: g++ -Wall -std=c++11 stack_overflow_1.cpp -o stack_overflow_1
- Run in Linux: ./stack_overflow_1
- */
- #include <iostream>
- void recurse(int count)
- {
- std::cout << count << "n";
- recurse(count + 1);
- }
- int main()
- {
- recurse(1);
- }
- /*
- recursion_until_stack_overflow
- - do a quick recursion test to see how many times I can make the call before the stack overflows
- Gabriel Staples
- Written: 6 Mar. 2018
- Updated: 7 Mar. 2018
- References:
- - Jumping Into C++, by Alex Allain, Ch. 16: Recursion, p.230
- */
- // Force the compiler to NOT optimize! Otherwise this recursive function below just gets optimized into a count++ type
- // incrementer instead of doing actual recursion with new frames on the stack each time. This is required since we are
- // trying to force stack overflow.
- // - See here for all optimization levels: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
- // - They include: -O1, -O2, -O3, -O0, -Os (Arduino's default I believe), -Ofast, & -Og.
- // I mention `#pragma GCC optimize` in my article here: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html
- #pragma GCC optimize ("-O0")
- void recurse(unsigned long count) // each call gets its own "count" variable in a new stack frame
- {
- // delay(1000);
- Serial.println(count);
- // It is not necessary to increment count since each function's variables are separate (so the count in each stack
- // frame will be initialized one greater than the last count)
- recurse (count + 1);
- // GS: notice that there is no base condition; ie: this recursive function, once called, will never finish and return!
- }
- void setup()
- {
- Serial.begin(115200);
- Serial.println(F("nbegin"));
- // First function call, so it starts at 1
- recurse (1);
- }
- void loop()
- {
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement