Dynamic Memory Allocation: The malloc() Function - C Memory

C examples for Memory:malloc

Introduction

The function that allocates memory at runtime is called malloc(). You need to include the stdlib.h header file to use this function.

When using the malloc() function, specify the number of bytes that you want allocated as the argument. The function returns the address of the first byte of memory that it allocated. For example,

int *pNumber = (int*)malloc(100);

The code above requests 100 bytes of memory and assigned the address of this memory block to pNumber.

pNumber will point to the first int location at the beginning of the 100 bytes. This whole block can hold 25 int values, because they require 4 bytes each.

The statement assumes that type int requires 4 bytes. To use the int type size, use the following statement.

int *pNumber = (int*)malloc(25*sizeof(int));

If the memory can't be allocated, malloc() returns a pointer with the value NULL. It's a good idea to check any dynamic memory request immediately.

int *pNumber = (int*)malloc(25*sizeof(int));
if(!pNumber)
{
  // Code to deal with memory allocation failure . . .
}

Related Tutorials