Dynamic Memory Allocation in C Programming

In all of our previous lessons, we have used static memory allocation in our programs. In this lesson, we will learn about Dynamic Memory Allocation in C Programming. Let’s first understand difference between Static Memory Allocation and Dynamic Memory Allocation. In Static Memory Allocation user requested memory will be allocated at compile time. Whereas In Dynamic Memory Allocation, memory will be allocated while executing programs that means at run time. The Dynamic Memory Allocation allows us to modify memory size at run time.

learn-embedded-system

Dynamic Memory Allocation in C Programming

Dynamic Memory Allocation is unique feature of C Programming Language. This allows us to create data types and structures of any size and length which suits our program. There are two common application of dynamic memory allocation, these are while using dynamic arrays and dynamic data structure e.g. linked lists in C Programs. Let’s see use case. There comes a situation in programming, when we don’t know exact size of array until compiler compiles the code and generate executable. The size of array we have declared maybe not enough or more than required. In this case use of dynamic memory allocation is best solution. Now the question is how to allocate dynamic memory? The answer is C Language supports 4 library functions which are knows as memory management functions (malloc, calloc, realloc, free). These functions are defined in #include<stdlib.h> header file. We will see each function in detail. Let’s first understand organization of application memory. The heap is a part of application memory which will be used while allocating and de-allocating memory using memory management functions. The Heap is also known as Free Memory. The figure below will illustrate.

Application Memory Organization
Application Memory Organization

The Heap memory is used for dynamic memory allocation during execution of the program. The size of heap memory keeps changing. As mentioned earlier heap is free pool of memory. This is enough as an introduction. The list of dynamic memory management functions.

Functions Syntax Description
malloc void* malloc(size_t size) Allocates the specified number of bytes user requested.
calloc void* calloc(size_t num, size_t size) Allocates the specified number of bytes and initialize them to zero
realloc void* realloc(void* ptr, size_t size) Modify the previously allocated memory block (increase or decrease memory size and reallocate)
free Release previously allocated memory block

malloc() – Allocate Block of Memory

malloc()” the name itself states “memory allocation”. The malloc() function allocate space in memory during run time of the program. Malloc() function does not not initialize memory space allocated at run time. If we try to access this memory, we will receive garbage value. Malloc() returns NULL Pointer, in case if it could not able to allocate requested amount of memory.

Example: Let’s have a look at simple example. We will define an array size of our choice. The use of malloc allows us to define size of array at run time.

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

int main()
{
    int n;
    printf("Enter the size of array: ");
    scanf("%d", &n);
    int *myArray = (int*) malloc(n*sizeof(int));

    for(int i=0; i<n; i++)
    {
        myArray[i] = i+1;
    }

    for(int i=0; i<n; i++)
    {
        printf("%d \t", myArray[i]);
    }
}

Explanation: When we build and run this example code. The message pop-up on screen to enter size of array and we have entered 10. As we are passing this value 10 to integer variable “n”. The int *myArray is pointer hold the address of first element of array. To allocate the size of array we have used malloc. In statement (int*) malloc(n*sizeof(int)) we have type cast the malloc. The malloc return void pointer and here we have an array of type integer. The output from this example code is shown as below.

output of malloc in c programming
Output of Malloc in C Programming

calloc() – Allocate Block of Memory

 calloc() function works similar as malloc(). The only difference between them is calloc() not only allocate memory block but also initialize the allocated memory to zero.

Example: Calloc() Dynamic Memory Allocation

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

int main()
{
    int n;
    printf("Enter the size of array: ");
    scanf("%d", &n);

    int *myArray = (int*) calloc(n, sizeof(n));

    for(int i=0; i<n; i++)
    {
        printf("%d \t", myArray[i]);
    }
}

This example is same as previous one. The only difference is the use of calloc function instead of malloc. Unlike previous example we are not going to assign any value to array i.e. int *myArray. Still when we read array elements, we will get 0 at all places. This shows that when we allocate memory using calloc, we need not to initialize this memory. The output of above program is given as below.

Output of Calloc in C Programming
Output of Calloc in C Programming

realloc() – Reallocate Block of Memory

Now we know how to allocate memory block. But what if previously allocated memory is not enough or more than require. In such case realloc(), allow to change size of previously allocated memory block. The realloc() simply allows us to modify the size of memory block at run time. If in case there isn’t enough free space in memory of current block to extend, new block is allocated for the full size of reallocation. In this case we copy existing data to new memory block and then free the old memory block.

Example: Extend the size of memory block A with size double as B.

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

int main()
{
    int n;
    printf("Enter the size of array: ");
    scanf("%d", &n);

    int *A = (int*) malloc(n*sizeof(int));
    for(int i=0; i<n; i++)
    {
        A[i]=i+1;
    }

    int *B = (int*) realloc(A, 2*n*sizeof(int));
    printf("Prev. block address= %d, New address= %d \n", A, B);

    for(int i=0; i<2*n; i++)
    {
        printf("%d \n", B[i]);
    }
}

Explanation: When we build and run this example code. The output of above program is given as below:

Output of Realloc in C Programming
Output of Realloc in C Programming

In this example when we enter size of array as 5. We get 10 numbers on screen. The first five are the element from memory block A and remaining 5 are garbage value at newly allocated space from block B. We also observe that starting address of block A and B are same. The reason is because while re-allocation of memory. The size of block extends from the previous address. That’s the reason why memory address remains same for both memory block A and B.

free() – Frees Block of Memory

The name of function free itself states its meaning. The function free(), frees the allocated memory by functions like malloc(), calloc() and realloc(). This newly freed memory return to system. This is recommended to use free explicitly to release memory. This is because dynamically allocated memory does not frees by its own. Let’s look at example code.

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

int main()
{
    int n;
    printf("Enter the size of array: ");
    scanf("%d", &n);

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

    for(int i=0; i<n; i++)
    {
        myArray[i]=i+1;
    }

    free(myArray);

    for(int i=0; i<n; i++)
    {
        printf("%d \t", myArray[i]);
    }
}

Explanation: The example code is exactly same as first program of this lesson. The only new statement in this code is free(myArray). We only need to pass the name of array i.e. myArray to function free. This function erase the data of that memory block (sometimes may not erase depending on your compiler or machine). But that memory will be available for allocation using malloc. So when we build and run this code we’ll get garbage value on screen.

This is it for Dynamic Memory Allocation in C Programming. We hope you have enjoyed reading this lesson. In next lesson, we’ll learn about Storage Classes in C Programming. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading.

Get Free Courses & Webinars
You'll receive only high quality learning material, tips & tricks
I agree to have my personal information transfered to MailChimp ( more information )
We respect your privacy

About Umesh Lokhande

Umesh Lokhande holds a Master degree in Scientific Instrumentation from University of Applied Sciences Jena, Germany. and has previously worked at Orbotech, Alere Technologies etc. Umesh is also a founder and first author of BINARYUPDATES.COM

Login

Register | Lost your password?