malloc function(Allocate Memory Block) in C Language – example and detail

In the C Programming Language, the malloc characteristic allocates a block of reminiscence for an array, however it does no longer clear the block. To allocate and clear the block, use the calloc function.

Syntax

The syntax for the malloc feature in the C Language is:

void *malloc(size_t size);

Parameters or Arguments

size

The size of the elements in bytes.

Returns

The malloc feature returns a pointer to the starting of the block of memory. If the block of reminiscence can now not be allocated, the malloc feature will return a null pointer.

Required Header

In the C Language, the required header for the malloc function is:

#include <stdlib.h>

Applies To

In the C Language, the malloc function can be used in the following versions:

ANSI/ISO 9899-1990

malloc Example

Let’s appear at an instance to see how you would use the malloc feature in a C program:

/* Example using malloc by TechOnTheNet.com */

/* The size of memory allocated MUST be larger than the data you will put in it */

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

int main(int argc, const char * argv[])
{
    /* Define required variables */
    char *ptr;
    size_t length;

    /* Define the amount of memory required */
    length = 50;

    /* Allocate memory for our string */
    ptr = (char *)malloc(length);

    /* Check to see if we were successful */
    if (ptr == NULL)
    {
        /* We were not so display a message */
        printf("Could not allocate required memory\n");

        /* And exit */
        exit(1);
    }

    /* Copy a string into the allocated memory */
    strcpy(ptr, "C malloc at TechOnTheNet.com");

    /* Display the contents of memory */
    printf("%s\n", ptr);

    /* Free the memory we allocated */
    free(ptr);

    return 0;
}

When compiled and run, this software will output:

C malloc at TechOnTheNet.com

Similar Functions

Other C features that are comparable to the malloc function:

calloc function free characteristic realloc characteristic