totn C Functions

C Language: malloc function
(Allocate Memory Block)

In the C Programming Language, the malloc function allocates a block of memory for an array, but it does not clear the block. To allocate and clear the block, use the calloc function.

Syntax

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

void *malloc(size_t size);

Parameters or Arguments

size
The size of the elements in bytes.

Returns

The malloc function returns a pointer to the beginning of the block of memory. If the block of memory can not be allocated, the malloc function 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 look at an example to see how you would use the malloc function 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 application will output:

C malloc at TechOnTheNet.com

Similar Functions

Other C functions that are similar to the malloc function: