Search code examples
cmemorymemory-managementdynamic-memory-allocationstatic-memory-allocation

Difference between static memory allocation and dynamic memory allocation


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

Could you explain this with any example?


Solution

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