To allocate a block of memory, call
malloc. The prototype for
this function is in stdlib.h.
Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock fd mem | See POSIX Safety Concepts.
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
calloc instead; see 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 Copying Strings and Arrays):
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 ISO 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 Representation of Strings, for more information about this.