C - malloc() - Dynamic Memory Allocation


malloc() Function

The simplest standard library function that allocates memory at runtime is called malloc().

When you use the malloc() function, you specify the number of bytes of memory as the argument.

The function returns the address of the first byte of memory that it allocated.

A typical example of dynamic memory allocation might be this:

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

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

This whole block can hold 25 int values on my computer, because they require 4 bytes each.

The following code uses int size as parameter:

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

The argument to malloc() is indicating that 25 values of type int should be made available.

If the memory that you request can't be allocated for any reason, malloc() returns a pointer with the value NULL.

We should check any dynamic memory request using an if statement to make sure the memory is actually there.

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

Related Topics