Difference between static memory allocation and dynamic memory allocation
Asked Answered
H

7

119

I would like to know what is the difference between static memory allocation and dynamic memory allocation?

Could you explain this with any example?

Hawkie answered 5/12, 2011 at 12:30 Comment(0)
R
111

There are three types of allocation — static, automatic, and dynamic.

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

void func() {
    int i; /* `i` only exists during `func` */
}

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.

int* func() {
    int* mem = malloc(1024);
    return mem;
}

int* mem = func(); /* still accessible */

In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:

free(mem);
Realtor answered 5/12, 2011 at 12:44 Comment(13)
Sure you have control over the lifetime of the variables... you're the one deciding the scope, right?Hedgcock
Of course, but that is not what I meant. You cannot extend the lifetime of the variables to outlive its scope. But maybe I should clarify that in my answer. ThanksRealtor
-1 This answer is wrong. You confuse static and automatic variables.Bankrupt
Your own sentence reads: "Static Allocation means, that the memory for your variables is automatically allocated" This is wrong. Have a look at what the manual page for GNU's libc has to say about it.Bankrupt
@Bankrupt the page you linked to isn't the C standard, is it. It's an implementation if I'm not mistaken. ;)Hedgcock
The word static should not be used in proximity to local variables.Aweigh
When you call this malloc() function is it giving the process more physical memory or is it just allocated a piece of virtual memory to store the variable. So for example, the process is 4 bytes and you malloc a byte, is the processes real physical memory 5 bytes now?Derringer
@LuchianGrigore yes, so whether static is automatic is implementation defined. Thus brice is right: static allocation doesn't neededly mean automatic allocation.Dunstan
I think both, brice and me have the problem with "automatically allocated". It's just 'there'. The problem is that (quoting the freely available n1256 C standard) "There are three storage durations: static, automatic, and allocated." -- If you say "static means automatically allocated" this just is mingling words that shouldn't go together. It's not "allocated" and neither is there something done really automatically, at least I wouldn't call it that.Dunstan
Stack allocation is not static. It happens dynamically at runtime, and depends on the runtime conditions of the program, rather than its statically-known properties (which is what static means in C and programming in general). Static allocation is what the compiler can infer, without actually running the program. I think you should rephrase your answer.Legalese
@EliBendersky It is rephrased now. Check if it is correct now.Vomit
@Bankrupt Answer Has Been Corrected finally.Vomit
@EliBendersky thanks man, you clarified a clear misunderstanding that is taught on many webpages: "stack memory allocaton occurs at compilation time", but how can that be? A function call, requiring stack memory, isn't made at compile-time, it's made during run-time. How can the compiler know how much stack memory to put aside for the things happening during that function call? Do correct me if I'm mistakenLatonia
B
139

This is a standard interview question:

Dynamic memory allocation

Is memory allocated at runtime using calloc(), malloc() and friends. It is sometimes also referred to as 'heap' memory, although it has nothing to do with the heap data-structure ref.

int * a = malloc(sizeof(int));

Heap memory is persistent until free() is called. In other words, you control the lifetime of the variable.

Automatic memory allocation

This is what is commonly known as 'stack' memory, and is allocated when you enter a new scope (usually when a new function is pushed on the call stack). Once you move out of the scope, the values of automatic memory addresses are undefined, and it is an error to access them.

int a = 43;

Note that scope does not necessarily mean function. Scopes can nest within a function, and the variable will be in-scope only within the block in which it was declared. Note also that where this memory is allocated is not specified. (On a sane system it will be on the stack, or registers for optimisation)

Static memory allocation

Is allocated at compile time*, and the lifetime of a variable in static memory is the lifetime of the program.

In C, static memory can be allocated using the static keyword. The scope is the compilation unit only.

Things get more interesting when the extern keyword is considered. When an extern variable is defined the compiler allocates memory for it. When an extern variable is declared, the compiler requires that the variable be defined elsewhere. Failure to declare/define extern variables will cause linking problems, while failure to declare/define static variables will cause compilation problems.

in file scope, the static keyword is optional (outside of a function):

int a = 32;

But not in function scope (inside of a function):

static int a = 32;

Technically, extern and static are two separate classes of variables in C.

extern int a; /* Declaration */
int a; /* Definition */

*Notes on static memory allocation

It's somewhat confusing to say that static memory is allocated at compile time, especially if we start considering that the compilation machine and the host machine might not be the same or might not even be on the same architecture.

It may be better to think that the allocation of static memory is handled by the compiler rather than allocated at compile time.

For example the compiler may create a large data section in the compiled binary and when the program is loaded in memory, the address within the data segment of the program will be used as the location of the allocated memory. This has the marked disadvantage of making the compiled binary very large if uses a lot of static memory. It's possible to write a multi-gigabytes binary generated from less than half a dozen lines of code. Another option is for the compiler to inject initialisation code that will allocate memory in some other way before the program is executed. This code will vary according to the target platform and OS. In practice, modern compilers use heuristics to decide which of these options to use. You can try this out yourself by writing a small C program that allocates a large static array of either 10k, 1m, 10m, 100m, 1G or 10G items. For many compilers, the binary size will keep growing linearly with the size of the array, and past a certain point, it will shrink again as the compiler uses another allocation strategy.

Register Memory

The last memory class are 'register' variables. As expected, register variables should be allocated on a CPU's register, but the decision is actually left to the compiler. You may not turn a register variable into a reference by using address-of.

register int meaning = 42;
printf("%p\n",&meaning); /* this is wrong and will fail at compile time. */

Most modern compilers are smarter than you at picking which variables should be put in registers :)

References:

Bankrupt answered 3/4, 2013 at 16:37 Comment(5)
Note: I'd suggest int * a = malloc(sizeof(*a)); instead, to avoid repeating the type of a. This makes things much easier if ever the type of a changes.Lovesick
Acutally it's called heap but it has nothing to do with heap data structure. Heap in this case means a messy placeNone
"Static memory allocation... Is allocated at compile time" Do you mean allocation size is determined at compile time? Wouldn't the setting aside of memory only happen at runtime?Coburg
Hey i have a doubt, If you are still responding :( . What about automatic memory allocation ? Will the compiler also store addresses in data section for these local variables and pass it to the executable. And when the code executes(and enters the scope) these addresses will actually be used as locations of allocated memory. Or does it actually gets allocated at run time only, without any address generation and handling by my compiler ?Raposa
@Raposa Automatic variables are scoped to the lifetime of the context (the curly braces) where they've been defined. that's usually allocated on the call stack at runtime. It's definitely not stored in the data section. You can read the C18 standard here: (6.2.4.5-7) web.archive.org/web/20181230041359/http://www.open-std.org/jtc1/…Bankrupt
R
111

There are three types of allocation — static, automatic, and dynamic.

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

void func() {
    int i; /* `i` only exists during `func` */
}

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.

int* func() {
    int* mem = malloc(1024);
    return mem;
}

int* mem = func(); /* still accessible */

In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:

free(mem);
Realtor answered 5/12, 2011 at 12:44 Comment(13)
Sure you have control over the lifetime of the variables... you're the one deciding the scope, right?Hedgcock
Of course, but that is not what I meant. You cannot extend the lifetime of the variables to outlive its scope. But maybe I should clarify that in my answer. ThanksRealtor
-1 This answer is wrong. You confuse static and automatic variables.Bankrupt
Your own sentence reads: "Static Allocation means, that the memory for your variables is automatically allocated" This is wrong. Have a look at what the manual page for GNU's libc has to say about it.Bankrupt
@Bankrupt the page you linked to isn't the C standard, is it. It's an implementation if I'm not mistaken. ;)Hedgcock
The word static should not be used in proximity to local variables.Aweigh
When you call this malloc() function is it giving the process more physical memory or is it just allocated a piece of virtual memory to store the variable. So for example, the process is 4 bytes and you malloc a byte, is the processes real physical memory 5 bytes now?Derringer
@LuchianGrigore yes, so whether static is automatic is implementation defined. Thus brice is right: static allocation doesn't neededly mean automatic allocation.Dunstan
I think both, brice and me have the problem with "automatically allocated". It's just 'there'. The problem is that (quoting the freely available n1256 C standard) "There are three storage durations: static, automatic, and allocated." -- If you say "static means automatically allocated" this just is mingling words that shouldn't go together. It's not "allocated" and neither is there something done really automatically, at least I wouldn't call it that.Dunstan
Stack allocation is not static. It happens dynamically at runtime, and depends on the runtime conditions of the program, rather than its statically-known properties (which is what static means in C and programming in general). Static allocation is what the compiler can infer, without actually running the program. I think you should rephrase your answer.Legalese
@EliBendersky It is rephrased now. Check if it is correct now.Vomit
@Bankrupt Answer Has Been Corrected finally.Vomit
@EliBendersky thanks man, you clarified a clear misunderstanding that is taught on many webpages: "stack memory allocaton occurs at compilation time", but how can that be? A function call, requiring stack memory, isn't made at compile-time, it's made during run-time. How can the compiler know how much stack memory to put aside for the things happening during that function call? Do correct me if I'm mistakenLatonia
S
3

Static Memory Allocation:

  • Variables get allocated permanently
  • Allocation is done before program execution
  • It uses the data structure called stack for implementing static allocation
  • Less efficient
  • There is no memory reusability

Dynamic Memory Allocation:

  • Variables get allocated only if the program unit gets active
  • Allocation is done during program execution
  • It uses the data structure called heap for implementing dynamic allocation
  • More efficient
  • There is memory reusability . Memory can be freed when not required
Synovia answered 5/12, 2011 at 12:40 Comment(1)
"Static Memory Allocation [...] It uses the data structure called stack for implementing static allocation" No, that's incorrect and misleading. please see my post for the difference between automatic and static allocation. Static memory may use the stack. This is strongly implementation dependent, and multiple strategies may be used for the same implementation. I'm not sure what you mean by "Less efficient" either. @Trieu Toan, you changed the meaning of this answer with a bad edit.Bankrupt
M
3

Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.

Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.

Murraymurre answered 5/12, 2011 at 14:40 Comment(0)
Y
1

Difference between STATIC MEMORY ALLOCATION & DYNAMIC MEMORY ALLOCATION

Memory is allocated before the execution of the program begins (During Compilation).
Memory is allocated during the execution of the program.

No memory allocation or deallocation actions are performed during Execution.
Memory Bindings are established and destroyed during the Execution.

Variables remain permanently allocated.
Allocated only when program unit is active.

Implemented using stacks and heaps.
Implemented using data segments.

Pointer is needed to accessing variables.
No need of Dynamically allocated pointers.

Faster execution than Dynamic.
Slower execution than static.

More memory Space required.
Less Memory space required.

Yeoman answered 4/1, 2013 at 7:58 Comment(2)
static memory allocation are allocated on Stack while the Dynamic memory allocation is allocated on HeapTrematode
@UsmanKurd That's generally incorrect regarding static memory. See my answer.Bankrupt
R
0

Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.

Ragout answered 18/4, 2017 at 8:31 Comment(0)
M
-1

Static memory allocation. Memory allocated will be in stack.

int a[10];

Dynamic memory allocation. Memory allocated will be in heap.

int *a = malloc(sizeof(int) * 10);

and the latter should be freed since there is no Garbage Collector(GC) in C.

free(a);
Mcdonough answered 5/12, 2011 at 12:42 Comment(1)
how can static memory be allocated on the stack when memory on the stack is dynamic? Variables can get "popped off" at any time ...Latonia

© 2022 - 2024 — McMap. All rights reserved.