Lets say I have a c program where I use only stack variables, no dynamic variables (malloc, ...)
Is it possible to calculate how much memory my program will ta开发者_开发问答ke during run time?
It not only depends on the OS and compiler like stated here.
It is simply impossible to determine it in advance in general.
If you make use of recursion calls, for example, you would have to know the parameters of these calls and it ends up in very complicated calculations that are impossible to make in advance if some parameters rely on user input or other unpredictable things.
Of course you could make some worst case scenario but generally the upper bounds are unlimited for most problems.
So only if your program is very simple and linear you can do so.
Yes, but the method of doing so depends on the OS. What platform are you targeting?
Yes - According to your compiler/os each object you put on the stack has a size (int - 4 bytes for example but it defers from compiler to compiler and from os to os) - you can use sizeof to find in runtime the size of what you put on the stack. Eventually the szie of the program will be the size of the code + the size of the stack you create. (finding the size of the code is harder, but you can just load the program and see in task manager how much it takes, this should give you some estimation if you're on window). I think the top will do it on linux.
If Linux such as FC9 etc, please see /proc/[PID]/maps, e.g.:
cat /proc/2738/maps
that'll make sense
It also depends on if how deep your call trace is. (Are you using recursive functions or not and so on.) Also, can your OS grow stacks?
There are CPU and memory profiling tools available that help you find how much CPU time or memory your program takes at run-time.
精彩评论