Maker Pro
Maker Pro

Let's talk about memory allocation

Dear all,

I have a question concerning memory allocation and I'd like to get it clear.

Memory allocation has types;
  • Static Memory Allocation:
  • Dynamic Memory Allocation:
If we want to store the number 100 we have to declare variable and then we have to assign value 100 to the variable

Does compiler allocate memory location to the value 100 of integer value ?

Where does it will store static memory or dynamic memory ?
 
There are actually 3 classes of memory in a typical compiled program. All are stored in the RAM of the computer.

static variable are allocated memory at compile time. These are all variables declared outside of a function and, in C/C++, those marked as static explicitly.

local variables of a function are allocated on a stack when the function is entered, and deallocated when the function exits. The next function called will reuse the same space.

dynamic allocation is when the program explicitly asks for memory for via a function call. The function returns a pointer, which the programmer must store somewhere. When finished, the programmer explicitly deallocates the memory, making it available for another allocation.

In systems with garbage collection, like Java, the runtime automatically deallocates dynamic memory when the are no more pointers that can access it.

Hope this helps.

Bob
 
There are actually 3 classes of memory in a typical compiled program. All are stored in the RAM of the computer.

static variable are allocated memory at compile time. These are all variables declared outside of a function and, in C/C++, those marked as static explicitly.

Hope this helps.

Bob
Thank you Bob
Code:
int global;
int main(void)
{
  int local;
}
Do you mean when we write the code, Compiler allocate memory location for the global and local variable at compiled time
 

Harald Kapp

Moderator
Moderator
It does for static variables as these must survive subroutine calls and returns.
It does not for automatic variables. Automatic variables need to be known only while a routine is active and are therefore placed on the stack (think of a scratchpad). An automatic variable becomes invalid once the routine has ended.

Think of a variable as simply a more convenient way of addressing a memory location. Using names suits human programmers so much more than using addresses.

This discussion may help you a bit further.
 
Thank you Bob
Code:
int global;
int main(void)
{
  int local;
}
Do you mean when we write the code, Compiler allocate memory location for the global and local variable at compiled time
No, I mean what I said in my post. Global variables are allocated at compile time, local variables are allocated when the function containing them is entered during execution.

Bob
 
Top