Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 688
Illusionist Avatar asked Dec 07 '22 10:12

Illusionist


2 Answers

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.

like image 79
Jack Avatar answered Dec 09 '22 15:12

Jack


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"...

like image 37
Robert Guyett Avatar answered Dec 09 '22 13:12

Robert Guyett