Study on Stack management during program running in windows
The following code draws a conclusion:
In a windows operating system, the stack space will not be released, but if the existing stack space meets the function running requirements, a new stack space will not be applied for, but the stack space will not be released after the function exits; if the function runtime space is insufficient, you need to apply for a new space;
The space dynamically applied using malloc is located in the heap space and can be directly released after free.
# Include <stdio. h>
# Include <Windows. h>
Int hello1 ()
{
Int arra [1000*60]; // The occupied stack space is approximately 0.2 MB.
Int I = 0;
For (I = 0; I <1000; I ++)
{
Arra [I] = 1024;
}
For (I = 0; I <40; I ++) // wait for 4 seconds
{
Sleep (100 );
Printf ("arra [% d] is % d \ n", arra [I]);
}
Return 0;
}
Int hello2 ()
{
Int arra [1000*150]; // The occupied stack space is approximately 0.5 MB.
Int I = 0;
For (I = 0; I <1000; I ++)
{
Arra [I] = 1024;
}
For (I = 0; I <40; I ++) // wait for 4 seconds
{
Sleep (100 );
Printf ("arra [% d] is % d \ n", arra [I]);
}
Return 0;
}
Int hello3 ()
{
Int arra [1000*100]; // The occupied stack space is approximately 0.4 MB.
Int I = 0;
For (I = 0; I <1000; I ++)
{
Arra [I] = 1024;
}
For (I = 0; I <40; I ++) // wait for 4 seconds
{
Sleep (100 );
Printf ("arra [% d] is % d \ n", arra [I]);
}
Return 0;
}
Int main ()
{
Int I = 56;
Int ret;
Char * tmp_buf;
Printf ("I is % d \ n", I );
For (I = 0; I <10; I ++)
{
Sleep (1000 );
Printf ("sleep % d seconds \ n", I );
}
// Before hello1 () execution, it is about 0.2 MB
Ret = hello1 ();
// After execution, it is about 0.4 MB
Hello2 ();
// After hello2 () is executed, it is approximately 0.7 MB
Hello3 ();
// After hello3 () is executed, it is still 0.7 MB, indicating that in windows, the stack space will continue to increase, but will not decrease, but it generally does not exceed the default stack size of the compiler (when programmers do not change)
Printf ("game over! ");
For (I = 0; I <5; I ++)
{
Printf ("over wait % d seconds \ n", I );
Sleep (1000 );
}
Tmp_buf = (char *) malloc (1024*1024 );
For (I = 0; I <5; I ++)
{
Printf ("over wait % d seconds \ n", I );
Sleep (1000 );
}
// Before tmp_buf is released, the memory occupied by the program is 1.8 MB.
Free (tmp_buf );
// After tmp_buf is released, when the program runs, the occupied memory size is 0.7 MB, which means free space can be directly released.
For (I = 0; I <5; I ++)
{
Printf ("over wait % d seconds \ n", I );
Sleep (1000 );
}
Return 0;
}