Skip to main content
Engineering LibreTexts

6: Memory management

  • Page ID
    40745
  • C provides 4 functions for dynamic memory allocation:

    • malloc, which takes an integer size, in bytes, and returns a pointer to a newly-allocated chunk of memory with (at least) the given size. If it can’t satisfy the request, it returns the special pointer value NULL.
    • calloc, which is the same as malloc except that it also clears the newly allocated chunk; that is, it sets all bytes in the chunk to 0.
    • free, which takes a pointer to a previously allocated chunk and deallocates it; that is, it makes the space available for future allocation.
    • realloc, which takes a pointer to a previously allocated chunk and a new size. It allocates a chunk of memory with the new size, copies data from the old chunk to the new, frees the old chunk, and returns a pointer to the new chunk.

    This API is notoriously error-prone and unforgiving. Memory management is one of the most challenging parts of designing large software systems, which is why most modern languages provide higher-level memory management features like garbage collection.

    • Was this article helpful?