Malloc Examples - The GNU C Library

Next: Freeing after Malloc, Previous: Basic Allocation, Up: Unconstrained Allocation

##### 3.2.2.2 Examples of `malloc`

If no more space is available, `malloc` returns a null pointer. You should check the value of every call to `malloc`. It is useful to write a subroutine that calls `malloc` and reports an error if the value is a null pointer, returning only if the value is nonzero. This function is conventionally called `xmalloc`. Here it is:

         void *
         xmalloc (size_t size)
         {
           register void *value = malloc (size);
           if (value == 0)
             fatal ("virtual memory exhausted");
           return value;
         }

Here is a real example of using `malloc` (by way of `xmalloc`). The function `savestring` will copy a sequence of characters into a newly allocated null-terminated string:

         char *
         savestring (const char *ptr, size_t len)
         {
           register char *value = (char *) xmalloc (len + 1);
           value[len] = '\0';
           return (char *) memcpy (value, ptr, len);
         }

The block that `malloc` gives you is guaranteed to be aligned so that it can hold any type of data. In the GNU system, the address is always a multiple of eight on most systems, and a multiple of 16 on 64-bit systems. Only rarely is any higher boundary (such as a page boundary) necessary; for those cases, use `memalign`, `posix_memalign` or `valloc` (see Aligned Memory Blocks).

Note that the memory located after the end of the block is likely to be in use for something else; perhaps a block already allocated by another call to `malloc`. If you attempt to treat the block as longer than you asked for it to be, you are liable to destroy the data that `malloc` uses to keep track of its blocks, or you may destroy the contents of another block. If you have already allocated a block and discover you want it to be bigger, use `realloc` (see Changing Block Size).