Dynamic Memory Allocation in C

In this tutorial, we will learn about Dynamic Memory Allocation in C. This method lets you request memory while your program is running. It is helpful when you don’t know how much memory you’ll need ahead of time. We will cover how to use functions like malloc(), calloc(), realloc(), and free() to manage memory effectively in your programs.

Contents:

  1. What is Dynamic Memory Allocation in C?
  2. Why Use Dynamic Memory Allocation in C?
  3. Functions for Dynamic Memory Allocation in C
  4. malloc() Function in C
  5. calloc() Function in C
  6. realloc() Function in C
  7. free() Function in C
  8. Difference Between malloc() and calloc() in C
  9. Common Mistakes and Best Practices in DMA
  10. FAQs on Dynamic Memory Allocation in C

What is Dynamic Memory Allocation in C?

Dynamic memory allocation (DMA) in C is the process of allocating memory while the program is running, using special functions. Unlike static memory allocation, which happens at compile-time, DMA allows a program to request memory as needed. This makes it a more efficient way to use memory.

Why Use Dynamic Memory Allocation in C?

  • Efficient Memory Usage: Static memory allocation sets memory in advance. This can waste memory if it’s not fully used. With dynamic memory allocation (DMA), you only ask for the memory you need, which saves space.
  • Handling Large Data Structures: Some data structures, like arrays, linked lists, trees, and graphs, need memory that the program doesn’t know about until it runs. DMA lets you create and resize these structures as needed.
  • Flexibility in Memory Management: With DMA, you can request memory when you need it and release it when you’re done. This helps save memory, especially in resource-limited systems.
  • Supports Variable-Sized Data Structures: When the number of elements changes, such as with user input, DMA helps manage it. For example, a program can read an unknown number of student records from a database.
  • Enables Dynamic Array Resizing: DMA allows arrays to change size. The realloc() function lets you resize arrays as the data grows or shrinks, saving memory.
  • Prevents Stack Overflow for Large Memory Needs: Stack memory is limited, which can cause stack overflow when the data is too large. DMA uses the heap, a larger memory area, to prevent overflow.

Functions for Dynamic Memory Allocation in C

The C Standard Library provides four functions for dynamic memory allocation, found in <stdlib.h>:

advertisement
Function Description
malloc() Allocates a block of memory but does not initialize it.
calloc() Allocates and initializes memory with zero.
realloc() Resizes previously allocated memory.
free() Deallocates the allocated memory to avoid memory leaks.

malloc() Function in C

The malloc() function in C is used for dynamic memory allocation. It allows a program to allocate a block of memory at runtime, making it useful for creating flexible data structures like dynamic arrays and linked lists.

Syntax:

void* malloc(size_t size);
  • size_t size: The number of bytes to allocate.
  • Returns a void* pointer to the allocated memory.
  • Returns NULL if memory allocation fails.

Key Features of malloc()

Free 30-Day Java Certification Bootcamp is Live. Join Now!
  • Allocates memory at runtime.
  • Returns a void pointer, which can be typecast to any data type.
  • Does not initialize the allocated memory (contains garbage values).
  • Requires free() to release memory and prevent memory leaks.

Example:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int *quizScores;
    int count, i;
 
    printf("Enter the number of quizzes: ");
    scanf("%d", &count);
 
    // Allocating memory dynamically
    quizScores = (int*) malloc(count * sizeof(int));
 
    if (quizScores == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
 
    // Taking input
    printf("Enter quiz scores:\n");
    for (i = 0; i < count; i++) {
        scanf("%d", &quizScores[i]);
    }
 
    // Displaying scores
    printf("Sanfoundry Quiz Scores: ");
    for (i = 0; i < count; i++) {
        printf("%d ", quizScores[i]);
    }
 
    free(quizScores); // Freeing memory
 
    return 0;
}

Output:

Enter the number of quizzes: 4
Enter quiz scores:
88 76 92 85
Sanfoundry Quiz Scores: 88 76 92 85

This C program asks the user for the number of quizzes. It then uses malloc() to create enough space in memory to store the quiz scores. After that, the program takes the quiz scores as input and shows them on the screen. Once done, it frees the memory to avoid any memory issues.

calloc() Function in C

The calloc() function in C is used for dynamic memory allocation. It allocates a specified number of blocks in memory, initializing all elements to zero. Unlike malloc(), which does not initialize memory, calloc() ensures that allocated memory starts with all bytes set to 0.

Syntax:

void* calloc(size_t num, size_t size);

Parameters:

advertisement
  • num → Number of elements to allocate.
  • size → Size of each element in bytes.

Return Value:

  • Returns a pointer to the allocated memory.
  • If memory allocation fails, it returns NULL.

Example:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int *scores;
    int numQuizzes, i;
 
    printf("Enter the number of quizzes: ");
    scanf("%d", &numQuizzes);
 
    // Allocating memory using calloc
    scores = (int*) calloc(numQuizzes, sizeof(int));
 
    if (scores == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
 
    // Input scores
    printf("Enter quiz scores:\n");
    for (i = 0; i < numQuizzes; i++) {
        scanf("%d", &scores[i]);
    }
 
    // Display scores
    printf("Quiz Scores: ");
    for (i = 0; i < numQuizzes; i++) {
        printf("%d ", scores[i]);
    }
 
    free(scores); // Free allocated memory
 
    return 0;
}

Output:

Enter the number of quizzes: 3
Enter quiz scores:
85 90 78
Quiz Scores: 85 90 78

This C program asks the user for the number of quizzes and uses calloc() to allocate memory for storing quiz scores. Unlike malloc(), calloc() also initializes the memory to zero. The program then takes quiz scores as input and displays them. Finally, it frees the memory to prevent memory leaks.

realloc() Function in C

The realloc() function in C is used to resize previously allocated memory dynamically. It allows you to increase or decrease the size of allocated memory without losing the existing data (up to the new size limit).

Syntax:

void* realloc(void* ptr, size_t new_size);

Parameters:

  • ptr → Pointer to the previously allocated memory block.
  • new_size → The new size (in bytes) for the memory block.

Return Value:

  • Returns a pointer to the newly allocated memory.
  • If new_size is 0, the memory is freed, and NULL is returned.
  • If realloc() fails, it returns NULL, and the original memory remains unchanged.

Example:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int *scores, i, numQuizzes;
 
    // Initial allocation for 3 quizzes
    numQuizzes = 3;
    scores = (int*) malloc(numQuizzes * sizeof(int));
 
    if (scores == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
 
    printf("Enter scores for %d quizzes:\n", numQuizzes);
    for (i = 0; i < numQuizzes; i++) {
        printf("Quiz %d: ", i + 1);
        scanf("%d", &scores[i]);
    }
 
    // Resize memory to accommodate more quiz scores
    printf("Enter new total quiz count: ");
    scanf("%d", &numQuizzes);
 
    scores = (int*) realloc(scores, numQuizzes * sizeof(int));
 
    if (scores == NULL) {
        printf("Memory reallocation failed!\n");
        return 1;
    }
 
    // Input additional scores if the size increased
    for (i = 3; i < numQuizzes; i++) {
        printf("Enter score for Quiz %d: ", i + 1);
        scanf("%d", &scores[i]);
    }
 
    printf("\nUpdated Quiz Scores:\n");
    for (i = 0; i < numQuizzes; i++) {
        printf("Quiz %d: %d\n", i + 1, scores[i]);
    }
 
    free(scores); // Free allocated memory
    return 0;
}

Output:

Enter scores for 3 quizzes:
Quiz 1: 85
Quiz 2: 90
Quiz 3: 78
Enter new total quiz count: 5
Enter score for Quiz 4: 88
Enter score for Quiz 5: 92
 
Updated Quiz Scores:
Quiz 1: 85
Quiz 2: 90
Quiz 3: 78
Quiz 4: 88
Quiz 5: 92

This C program shows how to allocate and resize memory. First, it allocates space for three quiz scores. The user enters scores for these three quizzes. Then, the program asks for the new number of quizzes and reallocates memory to fit this number. If successful, the user can enter more scores. Finally, the program shows all the quiz scores and frees the memory used.

free() Function in C

The free() function in C is used to deallocate memory that was previously allocated using malloc(), calloc(), or realloc(). It helps in preventing memory leaks by releasing unused memory back to the system.

Syntax:

void free(void *ptr);

ptr is the pointer to the memory block that needs to be freed.

Example:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int *scores;
 
    // Allocating memory for 5 quiz scores
    scores = (int*) malloc(5 * sizeof(int));
 
    if (scores == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }
 
    printf("Enter 5 quiz scores:\n");
    for (int i = 0; i < 5; i++) {
        printf("Quiz %d: ", i + 1);
        scanf("%d", &scores[i]);
    }
 
    // Displaying scores
    printf("\nStored Quiz Scores:\n");
    for (int i = 0; i < 5; i++) {
        printf("Quiz %d: %d\n", i + 1, scores[i]);
    }
 
    // Freeing allocated memory
    free(scores);
    printf("\nMemory has been deallocated successfully.\n");
 
    return 0;
}

Output:

Enter 5 quiz scores:
Quiz 1: 85
Quiz 2: 90
Quiz 3: 78
Quiz 4: 88
Quiz 5: 92
 
Stored Quiz Scores:
Quiz 1: 85
Quiz 2: 90
Quiz 3: 78
Quiz 4: 88
Quiz 5: 92
 
Memory has been deallocated successfully.

This C program allocates memory for 5 quiz scores using malloc. After allocating the memory, it asks the user to input scores for 5 quizzes. The scores are then displayed. Finally, the memory is freed using free, and a message is shown to confirm successful memory deallocation.

Difference Between malloc() and calloc() in C

Here is the difference between malloc() and calloc() in C:

Feature malloc() calloc()
Full Form Memory Allocation Contiguous Allocation
Memory Initialization Does not initialize memory (contains garbage values). Initializes memory to zero.
Syntax ptr = (int*) malloc(size_in_bytes); ptr = (int*) calloc(num_elements, size_of_each_element);
Number of Arguments Takes one argument (total size in bytes). Takes two arguments (number of elements and size of each element).
Performance Faster since it doesn’t initialize memory. Slightly slower due to zero initialization.
Use Case When memory initialization is not required (e.g., if values will be overwritten). When memory must be initialized to zero (e.g., arrays, structs).
Memory Contiguity Allocates a single continuous block of memory. Allocates multiple blocks and initializes them to `0`.
Return Value Returns NULL if allocation fails. Returns NULL if allocation fails.

Common Mistakes and Best Practices in DMA

  • Check if Memory Allocation Fails – malloc(), calloc(), or realloc() can return NULL if memory isn’t available. Always check before using the allocated memory to avoid crashes.
  • Free Memory After Use – If you allocate memory, don’t forget to free() it. Otherwise, your program may leak memory and slow down over time.
  • Avoid Using Memory After Freeing It – Accessing memory after calling free() leads to unpredictable behavior. To prevent this, set the pointer to NULL after freeing it.
  • Be Careful with realloc() – If realloc() fails, it returns NULL and doesn’t free the original memory. Store the result in a temporary pointer before assigning it to avoid losing the original data.
  • Use calloc() for Zero-Initialized Memory – malloc() gives you uninitialized memory with garbage values. If you need the memory to start with zeros, use calloc().
  • Don’t Free Memory Twice – Calling free() twice on the same pointer can cause errors or crashes. After freeing, set the pointer to NULL to avoid accidental double free.
  • Allocate Enough Space – If you don’t allocate enough memory, especially for strings, your program may overwrite memory it shouldn’t. Always account for extra space, like the \0 at the end of strings.
  • Only Free Heap Memory – You can only free() memory allocated with malloc(), calloc(), or realloc(). Trying to free stack memory (like local arrays) will cause errors.

FAQs on Dynamic Memory Allocation in C

1. What is dynamic memory allocation in C?
Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free(). It helps efficiently manage memory based on program needs.

2. How is dynamic memory different from static memory allocation?
Static memory allocation occurs at compile time, and memory size is fixed (e.g., arrays). Dynamic memory allocation happens at runtime, allowing flexible memory usage.

3. What happens if malloc() fails?
If malloc() fails due to insufficient memory, it returns NULL. Always check if the pointer returned is NULL before using it.

4. How is calloc() different from malloc()?
malloc() allocates memory without initializing it, meaning it may contain garbage values. calloc() allocates memory and initializes it to zero.

5. When should I use realloc()?
Use realloc() when you need to resize previously allocated memory without losing existing data. If it fails, the original memory remains unchanged.

6. What happens if I forget to call free()?
Forgetting to call free() results in memory leaks, where allocated memory is not returned to the system, leading to higher memory consumption.

7. What is a memory leak?
A memory leak occurs when allocated memory is never freed, leading to wastage and potential application slowdown over time.

8. Can I use free() on a NULL pointer?
Yes. Calling free(NULL) is safe and does nothing. This prevents accidental crashes when trying to free an unallocated pointer.

Key Points to Remember

Here is the list of key points we need to remember about “Dynamic Memory Allocation in C”.

  • Dynamic memory allocation allows memory to be requested during program execution, making memory usage more efficient and flexible.
  • malloc() allocates memory but doesn’t set it to anything, while calloc() allocates memory and fills it with zeros.
  • realloc() allows you to change the size of already allocated memory, keeping your data intact.
  • Always use free() to release memory once you’re done with it, and set the pointer to NULL to avoid mistakes.
  • Always check if malloc(), calloc(), or realloc() return NULL to make sure memory was successfully allocated.
  • Avoid errors like freeing memory twice, using freed memory, or not allocating enough space for your needs.
  • Use calloc() when you need memory to start as zero, and malloc() when you don’t need that.
  • Memory allocated by malloc() and calloc() is continuous, so make sure you allocate enough to avoid issues.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.