views:

373

answers:

5

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 take during run time?

A: 

Yes, but the method of doing so depends on the OS. What platform are you targeting?

Assaf Lavie
A: 

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.

Dani
Untrue, you are not accounting for stack alignment (can't push a single `char` on the stack and expect it to take 1 byte. Also you miss stuff the compiler puts on the stack for you, such as return addresses.
MSalters
A: 

If Linux such as FC9 etc, please see /proc/[PID]/maps, e.g.:

cat /proc/2738/maps

that'll make sense

EffoStaff Effo
A: 

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.

jdehaan
A: 

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?

Amigable Clark Kant