Illusionist
Illusionist

Reputation: 5489

How much memory does a function use?

I was asked this question in an interview- "how much memory does a function use?". So I tried to answer by saying you could add up all the memory taken by all the data variables , data structures it instantiates- for example add 4 bytes for long, 1 for char , 4 for int, 32 bits for a pointer on 32 bits system, and adding any inputs that were dynamically allotted. The interviewer was not happy with my answer.

I am learning C++, and will appreciate any insight.

Upvotes: 5

Views: 8400

Answers (4)

Bunny Pigtails
Bunny Pigtails

Reputation: 112

I bet the right answer could be "Undefined". An empty function consumes nothing.

function func(){}

A chaining one takes more than we can actually estimate.

function funcA()
{
   funcB();
   funcC();
   //...
}

A local object without being used in its scope will be optimized away by most compilers so it too takes zero memory in its container.

function func()
{
   var IamIgnored=0;
   //don't do anything with IamIgnored
}

And please don't miss the memory alignment so I think calculating memory used by an object or a function can't be simply done by accumulating all objects' memory sizes within their scopes.

Upvotes: 1

Pradeep Miriyala
Pradeep Miriyala

Reputation: 104

From point of view of static behavior, 1. Data used by it - Sum of all variables memory sizes 2. Size of instructions - Each instruction written inside a function will occupy some memory in binary. That is how size of your function will be identified. This is nothing but your compiled code size. From point of view of dynamic behavior (run time), 1. Heap memory resulted because of a function call is function memory.

Upvotes: 4

Robert Guyett
Robert Guyett

Reputation: 179

i think this guide on function footprints is what you were talking about. they were probably looking for "32/64 bits (integer) because its a pointer"...

Upvotes: 4

Jack
Jack

Reputation: 133597

Question is quite undefined. A function itself will occupy just the space for its activation record from the caller, for parameters and for its local variables on the stack. According to architecture the activation record will contain things like saved registers, address to return when the function is called and whatever.

But a function can allocate how much memory it requires on the heap so there is no a precise answer.

Oh in addition, if the function is recursive then it could use a lot of memory, always because of activation records which are needed between each call.

Upvotes: 7

Related Questions