Go to the previous, next section.

Basic Storage Allocation

To allocate a block of memory, call malloc. The prototype for this function is in `stdlib.h'.

Function: void * malloc (size_t size)

This function returns a pointer to a newly allocated block size bytes long, or a null pointer if the block could not be allocated.

The contents of the block are undefined; you must initialize it yourself (or use calloc instead; see section Allocating Cleared Space). Normally you would cast the value as a pointer to the kind of object that you want to store in the block. Here we show an example of doing so, and of initializing the space with zeros using the library function memset (see section Copying and Concatenation):

struct foo *ptr;
ptr = (struct foo *) malloc (sizeof (struct foo));
if (ptr == 0) abort ();
memset (ptr, 0, sizeof (struct foo));

You can store the result of malloc into any pointer variable without a cast, because ANSI C automatically converts the type void * to another type of pointer when necessary. But the cast is necessary in contexts other than assignment operators or if you might want your code to run in traditional C.

Remember that when allocating space for a string, the argument to malloc must be one plus the length of the string. This is because a string is terminated with a null character that doesn't count in the "length" of the string but does need space. For example:

char *ptr;
ptr = (char *) malloc (length + 1);

See section Representation of Strings, for more information about this.

Go to the previous, next section.