Dynamic memory allocation in c

Using pointers, we can allocate memory dynamically at runtime.

what is dynamic memory allocation? what is runtime?

Let's discuss the difference between static memory allocation and dynamic memory allocation.

Static memory allocation

If we decide the final size of a variable or an array before running the program, it will be called as static memory allocation. It is also called as compile-time memory allocation.

We can't change the size of a variable which is allocated at compile-time.


Example

#include<stdio.h>

int main()
{
    /*
     * compile time or static array allocation
     * we can't change the array size.
     * it is always 5.
     */

    int age[5]={17,19,18,20,21};

    return 0;
}

In the above program, we can't change the age array size based on our requirement. It always stores age of 5 students throughout the program execution. So if student size increases more than 5, we have to change the age array size manually every time.

To avoid that, we can allocate memory dynamically at runtime based on our requirement.

Dynamic memory allocation

At runtime, we can create, resize, deallocate the memory based on our requirement using pointers.

in the above code example, if student size increases, we can re-size the memory at runtime.If we don't need the age data at some point in time, we can free the memory area occupied by the age array.


C language provides different functions to achieve runtime memory allocation,

To allocate memory

malloc

calloc

To resize the memory

realloc

To deallocate memory

free




Topics You Might Like


Topics You Might Like