Dynamic Memory Allocation in C

In the context of of C family of languages, the word dynamic generally refers to doing stuff manually. And, in the case of Dynamic Memory Management, it rightly refer to performing manual memory management for a given set of data.

Programs are essentially run on computer memory. All processes have an unique number and each of this processes are allocated some amount of memory for performing their actions.

StackHeap.drawio (2).png

When it comes to C, there are two types of memory - stack and heap.

Stack

The stack is ordered and **all data on the stack has a fixed size that doesn’t change. Data of different types take up a definite amount of memory.

Exactly when and what order things are placed on the stack depends on how functions are called and when they return.

When a function is called, its local variables are placed on the stack, when it returns, they are removed.

The stack actually includes other information like memory locations for return values but we can ignore them for now.

Heap

The heap is for dynamic allocation of memory. We can request blocks of memory on the heap, of different sizes at runtime(when the program is executing).

Blocks of data on the heap can be of different sizes and not necessarily in order.

The heap grows from bottom to up while the stack grows downwards.

StackHeap-Page-2.drawio.png

Manual memory management

In C we need to manually manage memory on the heap by freeing space that we've requested after we're finished using it We call the free() function to free the memory allocated at a given memory address This type of memory management is called manual memory management

Manual memory management helps to improve performance, but comes at the cost of memory leaks

Memory Leaks

A memory leak can occur when we fail to free dynamically allocated memory.

Problem:

• The space is no longer available for our program to use

• Our program may no longer even have access to the space if the pointer referencing it no longer exists

Result:

• Performance can slow drastically, program can crash

• A "slow" memory leak can be difficult to detect

malloc and calloc

malloc stands for memory allocation and it takes number of bytes as its input param. It returns a pointer to the asked memory space.

calloc takes two params - the number of things and the size of those things. It differs from malloc in the sense that it at first zeros the memory spaces asked for. malloc does not do that. It keeps whatever junk is there in the memory space provides it to the program as it is.

calloc stands for contiguous allocation.

Resource

This video tutorial is awesome❣️:https://youtu.be/R0qIYWo8igs