Skip to main content
Engineering LibreTexts

12.3: Allocating Memory

  • Page ID
    35858
  • To use the memory routines, include the stdlib.h header in your code and be sure to link with the standard library. There are two main memory allocation functions. They are malloc() and calloc(). Here are their prototypes:

    void * malloc( unsigned int size );
    void * calloc( unsigned int num_item, unsigned int item_size );
    

    malloc() takes a single argument: The number of bytes that you wish to allocate from the free pool. calloc() takes two arguments: The number of items that you want to fit into the memory block and their size in bytes. Basically, calloc() just calls malloc() after multiplying the two arguments together. It is used for convenience. Both functions return a pointer to a type void. What is this? A void pointer can be thought of as a generic, one-size-fits-all pointer. It prevents possible type size clashes. You can assign a void pointer to another type of pointer and not get a type mismatch. If the memory request cannot be made (not enough memory) then the functions will return NULL. Always check for the NULL return! Never assume that the allocation will work!

    If you want to obtain space for 100 bytes, you’d do something like this:

    char *cp;
    
    cp = malloc( 100 );
    if( cp )
    {
        /* memory allocated, do stuff... */
    } else
    {
        /* not allocated, warn user and fail gracefully... */
    }
    

    If you need space for 200 doubles, you’d do something like this:

    double *dp;
    
    if( dp = calloc( 200, sizeof(double) ) ) /* assign and if test in 1 */
    {
        /* memory allocated, do stuff... */
    }
    else {
        /* not allocated, warn user and fail gracefully... */
    }
    

    Note the use of the sizeof() operator above. If you had a structure and needed to create one (for example, to add to a linked list), you might do this:

    struct foo *fp;
    
    if( fp = calloc( 1, sizeof(struct foo) ) )
    {
        /* remainder as above ... */
    
    • Was this article helpful?