Dynamic Memory Allocation in C Programming

Welcome to C Programming Tutorial

Your guide to getting started with C programming.

Dynamic Memory Allocation

Dynamic memory allocation in C allows you to manage memory at runtime, rather than at compile-time. This is particularly useful when you don't know the exact amount of memory you need until the program is running. The functions used for dynamic memory allocation are malloc(), calloc(), realloc(), and free(), but we'll focus on malloc() and free() in this example.

Dynamic Memory Allocation with malloc and free

1. malloc(): Memory Allocation

malloc() stands for "memory allocation." It is used to allocate a specified amount of memory during program execution. The syntax is:

void* malloc(size_t size);

2. free(): Deallocating Memory

free() is used to deallocate memory that was previously allocated with malloc(). The syntax is:

void free(void* ptr);

Example: Using malloc() and free()

#include <stdio.h>
#include <stdlib.h> // For malloc and free

int main() {
    // Allocate memory for an array of 5 integers
    int *arr = (int*)malloc(5 * sizeof(int));
    
    // Check if memory allocation was successful
    if (arr == NULL) {
        perror("Error allocating memory");
        return 1;
    }
    
    // Initialize and print the array
    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10; // Assigning values to the array
    }
    
    printf("Array elements:\n");
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]); // Printing values
    }
    printf("\n");
    
    // Deallocate the memory
    free(arr);
    
    return 0;
}
        

Explanation:

Memory Allocation with malloc():

int *arr = (int*)malloc(5 * sizeof(int));

Error Checking:

if (arr == NULL) {
    perror("Error allocating memory");
    return 1;
}

Initializing and Using the Array:

for (int i = 0; i < 5; i++) {
    arr[i] = i * 10;
}

Memory Deallocation with free():

free(arr);
Previous Next
Modern Footer