Back to course

Dynamic Memory Allocation (DMA): malloc() and calloc()

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 38: Dynamic Memory Allocation (DMA): malloc() and calloc()

Normal variables are allocated on the stack (fixed size). Dynamic memory is allocated on the Heap at runtime, allowing programs to manage memory sizes based on user input or operational needs. We use the <stdlib.h> library for DMA.

1. malloc() (Memory Allocation)

Allocates a block of memory of the specified size (in bytes) and returns a void * pointer to the beginning of the block. If allocation fails, it returns NULL.

Syntax: (type *) malloc(size_in_bytes);

c #include <stdlib.h>

// Allocate space for 10 integers int *arr_ptr = (int *) malloc(10 * sizeof(int));

if (arr_ptr == NULL) { // Handle error }

// The allocated memory block contains garbage values.

2. calloc() (Contiguous Allocation)

Allocates memory for an array of elements. It initializes all bytes in the allocated space to zero.

Syntax: (type *) calloc(number_of_elements, size_of_each_element);

c // Allocate space for 10 integers and initialize to 0 int *arr_ptr_zero = (int *) calloc(10, sizeof(int));

Key Difference: malloc allocates raw memory (garbage data); calloc allocates memory and zeros it out.