C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Pointers
  5. Dynamic Memory Allocation

Dynamic Memory Allocation

Dynamic memory allocation allows a program to request memory during runtime.

  • Unlike static memory (fixed at compile time), dynamic memory is allocated from the heap.
  • This helps manage memory more efficiently, especially for data structures like arrays or linked lists whose size may not be known beforehand.

Why Use Dynamic Memory Allocation?

  • To allocate memory when the size of data is unknown or changes during program execution.
  • To efficiently manage large or variable-size data.
  • To allocate memory for data structures like linked lists, trees, etc.

Functions for Dynamic Memory Allocation:

FunctionPurposeHeader File
malloc()Allocates specified number of bytes; returns pointer to the first byte. Memory is uninitialized.<stdlib.h>
calloc()Allocates memory for an array of elements, initializes all bytes to zero.<stdlib.h>
realloc()Changes the size of previously allocated memory block.<stdlib.h>
free()Frees the allocated memory, returning it to the system.<stdlib.h>

Syntax:

ptr = (castType*) malloc(size_in_bytes);
ptr = (castType*) calloc(num_elements, size_of_element);
ptr = (castType*) realloc(ptr, new_size);
free(ptr);
  • castType is usually the pointer type you want, e.g., int, float.
  • size_in_bytes is typically sizeof(data_type) * number_of_elements.

Example: Allocating and Using Dynamic Array:

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

int main() {
    int *arr;
    int n, i;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Allocate memory for n integers
    arr = (int*) malloc(n * sizeof(int));

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

    // Initialize array
    for (i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    // Print array elements
    printf("Array elements: ");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Free allocated memory
    free(arr);

    return 0;
}

How can we help?

Leave a Reply

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