C standard library function – malloc()

In case of static memory allocation there are some drawbacks like: wastage of memory, less flexibility, permanent allocation of variables etc. To overcome these situations the concept of Dynamic Memory Allocation has been introduced. In dynamic memory allocation the memories can be allocated dynamically at run time.

There 4 library functions that are described under <stdlib.h> (Standard Library Functions)

1. malloc()
2. calloc()
3. realloc()
4. free()

In this article we’ll deeply read about malloc().

What is malloc()?

To allocate memory dynamically we use the function which is called as malloc() function. malloc() function on success returns the base address of the allocated memory on failure it returns the NULL value. Every memory location will be initialized with a garbage value.

Memory allocation fails if sufficient memory is not provided. Unsuccessful memory allocation returns a NULL pointer (nullptr) to the pointer.

Syntax:

ptr = (datatype *)malloc((byte_size)*(number of elements))


For example, ptr = (int *)malloc(sizeof(int)*10)

It will create an array of 10 elements and will return the base address of the array. Every memory location will be initialized with a garbage value. This above statement will allocate 40 bytes of memory.

Example

/* C program to understand how malloc() works in DMA */
/* www.codewindow.in */

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

// Driver code
int main() {
	int n, i;  
	int *p;   // Integer pointer is declared
	
	printf("Enter a valid range: ");
	scanf("%d", &n);
	
	p=(int*)malloc(n*sizeof(int));   // An int array of n elements has been assigned to the pointer
	
    if(p == NULL) {                  // Checking if memory allocation is successful or not
	    printf("\nMemory allocation unsuccessful");
	    exit(0);
	}
	else {                          // Else memory allocation is successful
	    printf("\nMemory allocation successful");
	    printf("\nEnter the elements of array: ");
	
	    for(i=0; i<n; ++i)
		    scanf("%d", p+i);   // Array elements are taken as input
	
	    printf("\nElements of the array are: ");
	    for(i=0; i<n; i++)
		    printf("%d ", *(p+i));  // Print element of the array
	}
	return 0;
}

Input

Enter a valid range: 10
Enter the elements of array: 1 2 3 4 5 6 7 8 9 10 

Output

Memory allocation successful
Elements of the array are: 1 2 3 4 5 6 7 8 9 10 

Follow Us


You Missed

Also Checkout