OK - I can see what's happening in the second example. You need to look at initialisation of static vars. Basically your freememory() are only made the first time your 2 functions are called. Try this
void function1()
{
static int memory=freeMemory();
Serial.println(memory);
Serial.println(freeMemory());
function2();
}
void function2()
{
static int memory=freeMemory();
Serial.println(memory);
Serial.println(freeMemory());
function1();
}
Thank you Mark. This code works stable.
There is smaller shrinking RAM, but I don't understand why this method use memory?
If I have lots of functions linked each other...that mean the RAM will be consecutive shrunk?
Look up recursion. Every time you call a function from another, you consume stack space. Although there are circumstances when a function may call itself or a group of functions may make mutual calls to each other, it's not something you see often if you're using an UNO, precisely because it does not have much RAM.
In your case, function1 calls function2 and consumes a little space on the stack, then function2 calls function2 and uses some more. Then function1 calls function2 etc. etc and the depth of the call staqck increases until you consume all the RAM you have and crash.
highpiotr:
If I have lots of functions linked each other...that mean the RAM will be consecutive shrunk?
Each time your code makes a function call, it uses up a bit of memory on the stack to keep track of the call. Your code makes an unbounded number of function calls since you have two functions that call each other recursively without any limits. Inevitably, that code will keep making more and more calls until the stack has used up all available memory, and then fail.
Each time a function is called the return address is added to the stack, any vars local to the function are allso created on the stack. When you return from the function the stack used by the function is freed up.
You are calling the functions recursively and never allowing them to return. If your program where any more complex then it would crash!