Dynamic Memory Allocation | Memory Management in C

anuj_raghuwanshi_

Anuj Raghuwanshi

Posted on September 8, 2024

Dynamic Memory Allocation | Memory Management in C

A statically allocated variable or array has a fixed size in memory.

Dynamic Memory Allocation is a way in which the size of a data structure can be changed during the runtime.

Memory assigned to a program in a typical architecture can be broken down into four segments:

- Code
- Static/global variables
- Stack
- Heap

Dynamic memory allocation takes place in Heap.
Static memory allocation takes place in Stack.

Functions for dynamic memory allocation:

1. Malloc
2. Calloc
3. Realloc
4. Free

malloc() stands for memory allocation.

It reserves a block of memory with the given amount of bytes,sizeof operator is used.
Syntax:
ptr = (ptr-type*) malloc(size-in-bytes);

Image description

The return value is a void pointer to the allocated space.
Therefore, the void pointer needs to be casted to the appropriate type as per the requirements.
However, if the space is insufficient, allocation of memory fails and it returns a NULL pointer.
All the values at allocated memory are initialized to garbage values.

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

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

    printf("Enter size: \n");
    scanf("%d", &n);

    ptr = (int*) malloc(n * sizeof(int));

    for (int i = 0; i < n; i++) {
        printf("Enter the value no %d of array\n", i);
        scanf("%d", &ptr[i]);
    }

    for (int i = 0; i < n; i++) {
        printf("The value at %d is %d\n", i, ptr[i]);
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

calloc() stands for contiguous allocation.

It reserves n blocks of memory with the given amount of bytes.
It initializes each block with a default value ‘0’.
It has two parameters or arguments as compare to malloc().

Image description

The return value is a void pointer to the allocated space.
Therefore, the void pointer needs to be casted to the appropriate type as per the requirements.
However, if the space is insufficient, allocation of memory fails and it returns a NULL pointer.
Syntax:
ptr = (ptr-type*) calloc(n, size-in-bytes);

realloc() stands for reallocation.

If the dynamically allocated memory is insufficient, we can change the size of previously allocated memory using realloc() function.
Syntax:
ptr = (ptr-type*) realloc(ptr, new-size-in-bytes);

Image description

free()

free is used to free the allocated memory.
If the dynamically allocated memory is not required anymore, we can free it using free function.
This will free the memory being used by the program in the heap.
Syntax:
free(ptr)

Image description

💖 💪 🙅 🚩
anuj_raghuwanshi_
Anuj Raghuwanshi

Posted on September 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related