Dynamic memory allocation in C

Dynamic memory allocation in C

Dynamic memory allocation in C allows programs to obtain memory at runtime, which is essential for creating flexible and efficient applications. This is particularly useful when the size of the data structures (like arrays) cannot be determined at compile time. The standard library provides several functions to handle dynamic memory allocation, including malloc, calloc, realloc, and free.

Memory Allocation Functions

  1. malloc: Allocates a block of memory without initializing it.
  2. calloc: Allocates a block of memory and initializes all bytes to zero.
  3. realloc: Changes the size of an already allocated memory block.
  4. free: Deallocates a previously allocated block of memory.

Syntax and Examples

1. malloc (Memory Allocation)

  • Syntax: void* malloc(size_t size);
  • Description: Allocates size bytes of memory and returns a pointer to the allocated memory. The memory is not initialized.

Example:

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

int main() {
    int *ptr;
    int n = 5;

    // Allocating memory for 5 integers
    ptr = (int*) malloc(n * sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initializing allocated memory
    for (int i = 0; i < n; i++) {
        ptr[i] = i + 1;
    }

    // Printing the values
    for (int i = 0; i < n; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    // Freeing the allocated memory
    free(ptr);

    return 0;
}

2. calloc (Contiguous Allocation)

  • Syntax: void* calloc(size_t num, size_t size);
  • Description: Allocates memory for an array of num elements, each of size bytes, and initializes all bytes to zero.

Example:

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

int main() {
    int *ptr;
    int n = 5;

    // Allocating memory for 5 integers and initializing to 0
    ptr = (int*) calloc(n, sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Printing the values (all should be 0)
    for (int i = 0; i < n; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    // Freeing the allocated memory
    free(ptr);

    return 0;
}

3. realloc (Reallocation)

  • Syntax: void* realloc(void* ptr, size_t size);
  • Description: Changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged up to the minimum of the old and new sizes.

Example:

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

int main() {
    int *ptr;
    int n = 5, new_n = 10;

    // Allocating memory for 5 integers
    ptr = (int*) malloc(n * sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initializing allocated memory
    for (int i = 0; i < n; i++) {
        ptr[i] = i + 1;
    }

    // Reallocating memory to 10 integers
    ptr = (int*) realloc(ptr, new_n * sizeof(int));

    if (ptr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }

    // Initializing the newly allocated memory
    for (int i = n; i < new_n; i++) {
        ptr[i] = i + 1;
    }

    // Printing the values
    for (int i = 0; i < new_n; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    // Freeing the allocated memory
    free(ptr);

    return 0;
}

4. free (Deallocation)

  • Syntax: void free(void* ptr);
  • Description: Deallocates the memory previously allocated by a call to malloc, calloc, or realloc.

Example: The free function is used in the previous examples to deallocate the memory allocated by malloc, calloc, and realloc.

Important Points

  • Always check if the memory allocation was successful by checking if the returned pointer is NULL.
  • Always free dynamically allocated memory using the free function to avoid memory leaks.
  • When using realloc, if the new size is smaller, the remaining memory is freed; if the new size is larger, additional memory is allocated.

Example Program Combining All Functions

Here’s an example program that uses all the dynamic memory allocation functions:

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

int main() {
    int *ptr;
    int n = 5;

    // Using malloc to allocate memory
    ptr = (int*) malloc(n * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initializing and printing allocated memory
    for (int i = 0; i < n; i++) {
        ptr[i] = i + 1;
        printf("ptr[%d] = %d\n", i, ptr[i]);
    }

    // Using realloc to change the size of the memory block
    int new_n = 10;
    ptr = (int*) realloc(ptr, new_n * sizeof(int));
    if (ptr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }

    // Initializing and printing reallocated memory
    for (int i = n; i < new_n; i++) {
        ptr[i] = i + 1;
    }
    for (int i = 0; i < new_n; i++) {
        printf("ptr[%d] = %d\n", i, ptr[i]);
    }

    // Using calloc to allocate and initialize memory to zero
    int *ptr2 = (int*) calloc(new_n, sizeof(int));
    if (ptr2 == NULL) {
        printf("Memory allocation failed\n");
        free(ptr);  // Free previously allocated memory
        return 1;
    }

    // Printing the values of the calloc-allocated memory (all should be 0)
    for (int i = 0; i < new_n; i++) {
        printf("ptr2[%d] = %d\n", i, ptr2[i]);
    }

    // Freeing the allocated memory
    free(ptr);
    free(ptr2);

    return 0;
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *