Loading...

Memory Management in C

Memory management in C refers to allocating and freeing memory dynamically during program execution. C provides functions from the stdlib.h library for dynamic memory management.

Types of Memory Allocation

1. Static Memory Allocation

Memory is allocated at compile-time and cannot be resized during execution. Example:

int arr[10]; // Statically allocated array

2. Dynamic Memory Allocation

Dynamic memory allocation allows the allocation of memory at runtime using functions from the stdlib.h library. This is useful when the required memory size is unknown at compile time.

Memory Management Functions

C provides four functions for dynamic memory allocation:

  • malloc() - Allocates a block of memory
  • calloc() - Allocates multiple blocks and initializes them to zero
  • realloc() - Resizes allocated memory
  • free() - Deallocates memory

Using malloc()

malloc() allocates a single block of memory and returns a pointer.

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

int main() {
    int *ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers
    if (ptr == NULL) {
        printf("Memory allocation failed");
        return 1;
    }
    ptr[0] = 10; // Assign value
    printf("First element: %d", ptr[0]); // Outputs 10
    free(ptr); // Free allocated memory
    return 0;
}

Using calloc()

calloc() allocates multiple blocks and initializes them to zero.

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

int main() {
    int *ptr = (int*) calloc(5, sizeof(int)); // Allocates memory for 5 integers, initialized to 0
    if (ptr == NULL) {
        printf("Memory allocation failed");
        return 1;
    }
    printf("First element: %d", ptr[0]); // Outputs 0
    free(ptr); // Free allocated memory
    return 0;
}

Using realloc()

realloc() resizes previously allocated memory.

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

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

    // Reallocate memory
    ptr = (int*) realloc(ptr, 4 * sizeof(int));
    ptr[2] = 30;
    ptr[3] = 40;

    printf("Third element: %d", ptr[2]); // Outputs 30
    free(ptr);
    return 0;
}

Using free()

The free() function is used to release dynamically allocated memory.

free(ptr); // Frees allocated memory

Memory Management Best Practices

  • Always check if memory allocation was successful.
  • Use free() to release unused memory.
  • Avoid memory leaks by ensuring all allocated memory is freed.

Efficient memory management helps in optimizing performance and avoiding memory-related issues like leaks and segmentation faults.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!