Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Dynamic Memory Allocation in C

Introduction

Dynamic memory allocation in C allows programs to obtain memory space during runtime. This is crucial for applications where the amount of memory needed is not known at compile time. The C standard library provides several functions to allocate and free memory dynamically.

Memory Allocation Functions

There are four main functions used for dynamic memory allocation in C:

  • malloc()
  • calloc()
  • realloc()
  • free()

malloc()

The malloc() function allocates a specified number of bytes and returns a pointer to the first byte of the allocated space. The syntax is:

void* malloc(size_t size);

Example:

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

int main() {
    int *ptr;
    ptr = (int*)malloc(sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    *ptr = 10;
    printf("Value of ptr: %d\n", *ptr);
    free(ptr);
    return 0;
}
Output:
Value of ptr: 10

calloc()

The calloc() function allocates memory for an array of elements, initializes them to zero, and returns a pointer to the memory. The syntax is:

void* calloc(size_t num, size_t size);

Example:

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

int main() {
    int *ptr;
    ptr = (int*)calloc(5, sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    for (int i = 0; i < 5; i++) {
        printf("Value at ptr[%d]: %d\n", i, ptr[i]);
    }
    free(ptr);
    return 0;
}
Output:
Value at ptr[0]: 0
Value at ptr[1]: 0
Value at ptr[2]: 0
Value at ptr[3]: 0
Value at ptr[4]: 0

realloc()

The realloc() function changes the size of a previously allocated memory block. The syntax is:

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

Example:

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

int main() {
    int *ptr;
    ptr = (int*)malloc(2 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    ptr[0] = 1;
    ptr[1] = 2;

    ptr = (int*)realloc(ptr, 4 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }
    ptr[2] = 3;
    ptr[3] = 4;

    for (int i = 0; i < 4; i++) {
        printf("Value at ptr[%d]: %d\n", i, ptr[i]);
    }
    free(ptr);
    return 0;
}
Output:
Value at ptr[0]: 1
Value at ptr[1]: 2
Value at ptr[2]: 3
Value at ptr[3]: 4

free()

The free() function deallocates the memory previously allocated by a dynamic memory allocation function. The syntax is:

void free(void* ptr);

It is important to free dynamically allocated memory to avoid memory leaks.

Conclusion

Dynamic memory allocation is a powerful feature of the C language that allows programs to be more flexible and efficient in their memory usage. Understanding how to use malloc(), calloc(), realloc(), and free() is crucial for managing memory effectively in C programs.