malloc C Library Function

The function malloc allocates a continuous block of memory for an array of size bytes.Function malloc does not initializes the memory, it contains indeterminate values whereas calloc initializes the allocated memory with zero.

Function prototype of malloc

void *malloc(size_t size);
  • size : This is the size of memory block(in bytes) to allocate.

Return value of malloc

This function returns a pointer to the block of memory allocated by the malloc or null pointer If the function failed to allocate the requested block of memory. The type of returned pointer is always void*, which can be casted to any type of pointer.

C program using malloc function

The following program shows the use of malloc function to dynamically allocate an array.

malloc C Library Function

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    int *array, counter, n;
    int arraySize, sum=0;
     
    printf("Enter number of elements\n");
    scanf("%d", &n);
    /* Calculate size of array to store n integers */
    arraySize = n*sizeof(int);
    /* Allocate memory to store n integers using malloc */
    array = (int*)malloc(arraySize);
    /* 
     * Take n integers as input from user and store 
     * them in array 
     */
    printf("Enter %d numbers\n", n);
    for(counter = 0; counter < n; counter++){
        scanf("%d", &array[counter]);
    }
    /* Find sum of n numbers */
    for(counter = 0; counter < n; counter++){
        sum = sum + array[counter];
    }
    printf("Sum of %d numbers : %d", n, sum);
     
    return 0;
}

Output

Enter number of elements
5
Enter 5 numbers
1 2 3 4 5
Sum of 5 numbers : 15