#include<stdlib.h>
void *malloc(size_t sz); void *aligned_alloc (size_t aln, size_t sz);
malloc
and
aligned_
allocate sz
bytes of memory, returning a pointer
to the first byte. To allocate memory for a single
object, apply the operator
sizeof
to its type to get the minimum
number of bytes required by the type:
struct point { int x, y; }; struct point *p1 = malloc(sizeof(struct point)); struct point *p2 = aligned_alloc (alignof(struct point), sizeof(struct point));
Because sizeof
can also take an
expression
which doesn't get (fully) evaluated, you can safely
dereference the variable to be used to hold the object's
address:
struct point *p1 = malloc(sizeof *p1);
This obviates having to restate the type of the object, and it doesn't have to be changed if the variable's type changes.
The alignment of a pointer returned by
aligned_
has a minimum of
aln
, which much be a supported
alignment, and sz
must be a
multiple of it. The alignment of a pointer returned by
malloc
is suitable for all types.
If an allocation fails, NULL
is returned. A program
must check for this before using the pointer. It's good
practice to write specific functions to allocate objects
of specific types, so that allocation and initialization
are kept together:
struct point *alloc_point(int x, int y) { struct point *ptr = malloc(sizeof *ptr); if (ptr == NULL) return NULL; ptr->x = x; ptr->y = y; return ptr; }