C - Introducing the malloc() function

Introduction

malloc() allocates memory in a given size to store a certain variable type.

Here's the format:

p = (type *)malloc(size); 

type is a typecast, directing malloc() to allocate a chunk of memory sized to store the proper amount of information for the given variable type.

size is the quantity of storage that's needed.

It's measured in bytes, but you have to allocate enough storage to accommodate the variable type.

The malloc() function returns the address of the chunk of memory that's allocated.

The address is stored in pointer p, which must match the variable type.

When memory can't be allocated, a NULL value is returned.

You must check for the NULL before you use the allocated memory.

Demo

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

int main() /*w  w w  . j  ava  2  s  .c o  m*/
{ 
    int *age; 

    age = (int *)malloc(sizeof(int)*1); 
    if(age == NULL) 
    { 
        puts("Unable to allocate memory"); 
        exit(1); 
    } 
    printf("How old are you? "); 
    scanf("%d",age); 
    printf("You are %d years old.\n",*age); 
    return(0); 
}

Result

The code uses malloc() to set storage for one integer.

To ensure that the proper amount of storage is allocated, the sizeof operator is used.

To allocate space for one integer, the value 1 is multiplied by the result of the sizeof(int) operation.

The address of that storage is saved in the age pointer.

The code tests to ensure that malloc() was able to allocate memory.

If not, the value returned is NULL, and the program displays an error message and quits.

Related Topic