Dynamic Memory Allocation in C Programming

CCBeginner
Practice Now

Introduction

In C programming, we may not always know the initial size of an array beforehand. In such cases, we use dynamic memory allocationโ€”a method of allocating memory only when necessary. malloc() is a function used in C programming to allocate a specific amount of memory needed for an array or a variable that will be used at run time. In this lab, we will be learning how to allocate memory dynamically using malloc() and then clear out the memory space using free().

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Include necessary header files

In this step, we will include the necessary header files in our program.

#include <stdio.h>
#include <stdlib.h>

Define the main() function

In this step, we will define the main() function. In this function, we will declare the variables needed for the program.

int main()
{
    int n, i, *ptr, sum = 0;

    printf("\nEnter number of elements: ");
    scanf("%d", &n);

Allocate memory dynamically using malloc()

In this step, we will allocate memory dynamically using malloc(). The size of memory to be allocated is determined by the product of the number of elements and the size of each element using the sizeof() operator.

ptr = (int *) malloc(n * sizeof(int));

if(ptr == NULL)
{
    printf("\nError! Memory not allocated.");
    exit(0);
}

Store values in the allocated memory

In this step, we will store values in the allocated memory using a loop.

for(i = 0; i < n; i++)
{
    printf("\nEnter element %d: ", i + 1);
    scanf("%d", ptr + i);
    sum += *(ptr + i);
}

Print the values

In this step, we will print the values that have been stored.

printf("\nElements entered are: ");
for(i = 0; i < n; i++)
{
    printf("%d ", *(ptr + i));
}

Release the memory

In this step, we will release the allocated memory using free().

free(ptr);

Summary

In this lab, we learned how to allocate memory dynamically using malloc() and clear out the memory space using free(). We learned how to declare variables in the main() function and allocate memory using malloc(). We also learned how to store data in the allocated memory space, print the values stored, and then release the memory allocated using free().

Other C Tutorials you may like