How much memory does the function use?

I was asked this question in an interview: "How much memory does the function use?" So I tried to answer by saying that you can add all the memory received by all the data variables, the data structures that it creates, for example, add 4 bytes in length, 1 for char, 4 for int, 32 bits for a pointer to a 32 bit system and adding any inputs that have been dynamically allocated. The interviewer was unhappy with my answer.

I am learning C ++ and would appreciate an understanding.

+4
source share
4 answers

In terms of static behavior, 1. The data he uses is the sum of all variable memory sizes 2. The size of the instructions. Each instruction written inside the function will occupy some memory in binary format. This is how the size of your function will be determined. This is nothing like your compiled code size. From the point of view of dynamic behavior (runtime) 1. The heap memory caused by a function call is a functional memory.

+2
source

The question is pretty undefined. The function itself will occupy only space for its activation record from the caller, for parameters and for its local variables on the stack. According to the architecture, the activation record will contain such things as stored registers, address to return when the function is called, etc.

But a function can allocate how much memory is needed on the heap, so there is no exact answer.

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

+6
source

I think this footprints feature guide is what you were talking about. they were probably looking for "32/64 bit (integer), because the pointer" ...

+4
source

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

function func(){} 

The chain takes more than we can really appreciate.

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

A local object that is not used in its area will be optimized by most compilers, so it also takes up zero memory in its container.

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

And please do not skip memory alignment, so I think that calculating the memory used by an object or function cannot simply be done by accumulating all the memory sizes of objects within their areas.

+1
source

Source: https://habr.com/ru/post/1447391/


All Articles