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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/PointersandMemoryGroup -.-> c/pointers("`Pointers`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/variables -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/data_types -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/operators -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/if_else -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/for_loop -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/user_input -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/memory_address -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/pointers -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/function_parameters -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} c/function_declaration -.-> lab-123283{{"`Dynamic Memory Allocation in C Programming`"}} end

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