Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Allocation

Tags:

c++

When we 'define' a variable inside a function (not main here), is the memory allocation done at runtime or the loader serves for us??

And what happens when i have :

int f()
{
     int a=10;

     ........
}

main()
{
     int i;
     scanf("%d",&i);
     while(--i)
         f();
      ..........
}

Is 'a' in function f() created 'i' times?? And so is it dynamic allocation??

like image 366
letsc Avatar asked Jun 17 '26 18:06

letsc


2 Answers

The local variable a is made during each call of f(). It is part of setting up the 'stack-frame' for f() and costs (almost) nothing in time. It eats up a little stackspace, but no more than is necessary for an int.

During while(--i) f(); the function f() is called 10 times and each time a 'new' a occupies the same spot of memory. We do not call this dynamic allocation, it is called stack, local or auto allocation.

like image 171
Henk Holterman Avatar answered Jun 19 '26 07:06

Henk Holterman


This is a stack allocation, meaning that place is reserved on the stack for the integer - it's not allocated like "find 4 free bytes on the heap and allocate them for me".

like image 37
Eldad Mor Avatar answered Jun 19 '26 07:06

Eldad Mor