Difference between static memory allocation and dynamic memory allocation

319,888

Solution 1

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);

Solution 2

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:

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

Solution 4

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

Solution 5

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.

Share:
319,888

Related videos on Youtube

Nishant Kumar
Author by

Nishant Kumar

Present-: Lead FullStack Engineer at Concular (Berlin) As of now I am venturing and devoting most of my time to bringing Circular Economy in construction tech, at Concular I am responsible for the entire Concular Product infrastructure and engineering team. Education: Master Degree in software system from BITS Pilani Key Skill: Node.js, Go, React, redux JavaScript, Typescript, mongoDB, TDD, AWS , Terraform, dynamoDB, Elasticsearch, Functional Programming, Domain Driven Design, FluentD prometheus, kubernetes, EKS, CircleCI, Bitbucket, GitLab, Heroku, Microservices

Updated on August 28, 2020

Comments

  • Nishant Kumar
    Nishant Kumar over 3 years

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

    Could you explain this with any example?

  • Luchian Grigore
    Luchian Grigore over 12 years
    Sure you have control over the lifetime of the variables... you're the one deciding the scope, right?
  • Constantinius
    Constantinius over 12 years
    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. Thanks
  • Usman Kurd
    Usman Kurd over 11 years
    static memory allocation are allocated on Stack while the Dynamic memory allocation is allocated on Heap
  • brice
    brice about 11 years
    -1 This answer is wrong. You confuse static and automatic variables.
  • Shahbaz
    Shahbaz about 11 years
    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.
  • brice
    brice about 11 years
    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.
  • Luchian Grigore
    Luchian Grigore about 11 years
    @brice the page you linked to isn't the C standard, is it. It's an implementation if I'm not mistaken. ;)
  • Peter - Reinstate Monica
    Peter - Reinstate Monica about 10 years
    The word static should not be used in proximity to local variables.
  • Ogen
    Ogen over 9 years
    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?
  • dynamic
    dynamic over 9 years
    Acutally it's called heap but it has nothing to do with heap data structure. Heap in this case means a messy place
  • ljrk
    ljrk about 8 years
    @LuchianGrigore yes, so whether static is automatic is implementation defined. Thus brice is right: static allocation doesn't neededly mean automatic allocation.
  • ljrk
    ljrk about 8 years
    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.
  • Eli Bendersky
    Eli Bendersky almost 8 years
    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.
  • Suraj Jain
    Suraj Jain almost 8 years
    @EliBendersky It is rephrased now. Check if it is correct now.
  • Suraj Jain
    Suraj Jain almost 8 years
    @brice Answer Has Been Corrected finally.
  • lf215
    lf215 almost 7 years
    "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?
  • brice
    brice over 4 years
    "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.
  • brice
    brice over 4 years
    @UsmanKurd That's generally incorrect regarding static memory. See my answer.
  • LocalHost
    LocalHost over 3 years
    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 ?
  • brice
    brice over 3 years
    @LocalHost 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/j‌​tc1/…
  • Abdel Aleem
    Abdel Aleem about 3 years
    @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 mistaken
  • Abdel Aleem
    Abdel Aleem over 2 years
    how can static memory be allocated on the stack when memory on the stack is dynamic? Variables can get "popped off" at any time ...