Dynamic memory allocation

Dynamic Memory Allocation Functions

1. malloc

malloc (memory allocation) allocates a specified number of bytes of memory and returns a pointer to the beginning of the allocated block.

Syntax:

void *malloc(size_t size);
  • size: Number of bytes to allocate.

Example:

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

int main() {
    int *arr = (int *)malloc(5 * sizeof(int));  // Allocate memory for 5 integers
    
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Use the allocated memory
    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
        printf("%d ", arr[i]);  // Outputs: 0 10 20 30 40
    }
    
    free(arr);  // Free the allocated memory
    
    return 0;
}

2. calloc

calloc (contiguous allocation) allocates memory for an array of elements, initializes all bytes to zero, and returns a pointer.

Syntax:

  • num: Number of elements.

  • size: Size of each element in bytes.

Example:

3. realloc

realloc (reallocation) changes the size of a previously allocated memory block. It may move the block to a new location.

Syntax:

  • ptr: Pointer to the previously allocated memory block.

  • newSize: New size in bytes.

Example:

4. free

free releases a block of memory previously allocated by malloc, calloc, or realloc.

Syntax:

  • ptr: Pointer to the memory block to be freed.

Example:


Dynamic Arrays

Dynamic arrays are arrays whose size can be adjusted at runtime using the above memory allocation functions.

Example: Dynamic Array Creation and Resizing

Explanation:

  • Allocate: malloc allocates initial memory for 3 integers.

  • Resize: realloc increases the array size to 6 integers.

  • Use: Initialize and access the dynamic array elements.

  • Free: free releases the memory when done.


Summary

  • malloc: Allocates memory.

  • calloc: Allocates and initializes memory.

  • realloc: Resizes previously allocated memory.

  • free: Releases allocated memory.

  • Dynamic Arrays: Created and resized at runtime using these functions.

Last updated