Malloc

From LQWiki
Jump to navigation Jump to search

The malloc utilities in the C standard library are used to achieve dynamic memory allocation. Normally, in C, memory is created and released with the stack -- that is, a fixed block of memory can be allocated when one enters a function, but is released and must be released when the function returns. This form of memory management however is somewhat inflexible, and dynamic memory allocation with utilities such as malloc alleviate this necessity.

The malloc function is used to return a pointer to the block of memory dynamically allocated. It takes one argument -- the size of the block of memory in bytes to allocate. It returns a void *, that is, a raw pointer to memory, and must be cast to the correct type of pointer when used. Since one includes the stdlib.h header when one wishes to use malloc, the cast is done automatically.

For an example of typical usage, consider the following example

#include <stdio.h>
#include <string.h>

int 
main(void)
{
   char str[20];

   strcpy(str, "Hello!");
   printf("%s\n", str);
 
   return 0;
}

can equivalently be written

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

int
main(void)
{
   char *str = malloc(sizeof(char)*20);
   
   strcpy(str, "Hello!");
   printf("%s\n", str);
   
   return 0;
}

Note that some data type may not take up one byte exactly, so it is a common idiom to give the size argument to malloc in terms of sizeof(type)*no_of_type.

If malloc fails to allocate memory, it will return NULL.

There are other dynamic memory allocation functions available, such as

  • realloc, which can grow or shrink a chunk of memory as needed
  • calloc, which can zero a chunk of memory (or, one can use malloc and memset in tandem)