How to allocate dymanic memory using malloc function in C

C Dynamic Memory Allocation

In C programming, dynamic memory allocation is a way for programs to request memory from the operating system during runtime.

It is useful when the program doesn't know in advance how much memory it will need.

Dynamic memory is allocated on the heap during the program's execution.

It enables the creation of data structures like arrays or linked lists whose size can change during runtime.

It is used for flexiable memory size, efficient memory usage and dynamic data structures.

malloc() Function for Dynamic Memory Allocation

The C standard library provides malloc() function to allocate dynamic memory allocation in the <stdlib.h> header file.

malloc() function allocates a block of memory of the specified size in bytes and returns a pointer to the memory.

The function does not initialize the memory and contains garbage values.

It is very crucial to check whether the malloc() function allocates the requested memory. Otherwise it will lead to undefined behavior. In most cases, this will result in a segmentation fault and your program will crash. Error checking is a fundamental part of writing high-quality software.

Syntax of malloc() Function

void*: A generic pointer is returned, which will be typically cast to the appropriate data type by the programmers.

size: The number of bytes to allocate for the block of memory

Example of malloc() Function
Output of the above example
5
7
9
10

Explanation of code:

  • int *ptr = (int *)malloc(4 * sizeof(int));: This line allocates memory for 4 interger numbers.
  • if (ptr == NULL): This is a crucial error checking. If malloc() function fails to allocate the requested memory due to some reasons, it will return NULL.
  • ptr[0] = 5;...ptr[3] = 10;: These lines assign values to the elements of the dynamically allocated array.
  • for (int i = 0; i < 4; i++){...}: This loop iterates through the array and prints each element.
  • free(ptr);: The free() function deallocates the memory previously allocated by malloc(). The function takes the pointer ptr as argument.
  • ptr = NULL;: Setting the pointer ptr to NULL after freeing it is good practice to avoid dangling pointers.

The free() function is crucial in dynamic memory management process because it deallocates the memory that was previously allocated dynamically. By deallocating memory with free() function, it is ensured that the program uses memory efficiently. In severe cases, memory leaks can exhaust the available memory resources, leading to system instability and crashes.

Live Code Playground

In the following C code editor, you can practice by allocating memory using malloc() function. Click the 'Execute' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output