Nishant Nishant - 3 months ago 37
C Question

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?

Answer

Static Allocation means, that the memory for your variables is automatically allocated, either on the Stack or in other sections of your program. You do not have to reserve extra memory using them, but on the other hand, have also no control over the lifetime of this memory. E.g: a variable in a function, is 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 it, at some point cannot allocation 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);