Next: Compile-time Assertions, Previous: alloca-opt, Up: Particular Modules [Contents][Index]
The standard C library malloc/realloc/calloc/free APIs are prone to a
number of common coding errors. The safe-alloc
module provides
macros that make it easier to avoid many of them. It still uses the
standard C allocation functions behind the scenes.
Some of the memory allocation mistakes that are commonly made are
malloc
, especially
when allocating an array,
malloc
and realloc
for
errors,
malloc
,
free
by forgetting to set the pointer
variable to NULL
,
realloc
when that call fails.
The safe-alloc
module addresses these problems in the following way:
__warn_unused_result__
attribute.
calloc
instead of malloc
.
Allocate sizeof(*ptr)
bytes of memory and store the address of
allocated memory in ptr
. Fill the newly allocated memory with
zeros.
Returns -1 on failure, 0 on success.
Allocate an array of count
elements, each sizeof(*ptr)
bytes long, and store the address of allocated memory in
ptr
. Fill the newly allocated memory with zeros.
Returns -1 on failure, 0 on success.
Allocate an array of count
elements, each sizeof(*ptr)
bytes long, and store the address of allocated memory in
ptr
. The allocated memory is not initialized.
Returns -1 on failure, 0 on success.
Reallocate the memory pointed to by ptr
to be big enough to hold
at least count
elements, each sizeof(*ptr)
bytes long,
and store the address of allocated memory in ptr
. If
reallocation fails, the ptr
variable is not modified.
Returns -1 on failure, 0 on success.
Free the memory stored in ptr
and set ptr
to
NULL
.
Next: Compile-time Assertions, Previous: alloca-opt, Up: Particular Modules [Contents][Index]